我有兩個在命令列上連接的表。我需要更新表 1,其中表 2 中的專案與 id 有多個匹配項。
表 1 items:
------------------- ------------------ ------ ----- --------------------- -------------------
| Field | Type | Null | Key | Default | Extra |
------------------- ------------------ ------ ----- --------------------- -------------------
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| vendors_id | tinyint unsigned | NO | MUL | NULL | |
| multiple_vendors | tinyint unsigned | NO | MUL | NULL | |
------------------- ------------------ ------ ----- --------------------- -------------------
表 2 item_details:
| Field | Type | Null | Key | Default | Extra |
------------------- ------------------ ------ ----- ------------------- -------------------
| itmes_id | int unsigned | NO | PRI | NULL | |
| vendors_id | tinyint unsigned | NO | PRI | NULL | |
| location | varchar(255) | YES | MUL | NULL | |
| color | varchar(255) | YES | MUL | NULL | |
| description_short | varchar(255) | YES | MUL | NULL | |
| description_long | text | YES | | NULL | |
------------------- ------------------ ------ ----- ------------------- -------------------
表items和item_details表通過 item_details.items_id = items.id 連接。
item_details來自不同供應商的單個專案可能有多個整體。如果我有來自多個供應商的商品,我想更新items.multiple_vendors = 1。我試圖弄清楚如何在items該檢查上運行更新 if count(item_details.vendors_id > 1。
我正在嘗試使用以下查詢,但是我收到了錯誤 ERROR 1111 (HY000): Invalid use of group function
update items i left join item_details id on id.items_id = i.id set i.multiple_vendors = 1 where count(distinct(id.vendors_id)) > 1 ;
提前感謝您的幫助~
uj5u.com熱心網友回復:
您不能在 中使用聚合函式WHERE,因為只有在您選擇行之后才會發生聚合。
加入僅回傳具有多個匹配項的行的子查詢。
UPDATE items AS i
JOIN (
SELECT items_id
FROM item_details
GROUP BY items_id
HAVING COUNT(DISTINCT vendors_id) > 1
) AS id ON id.items_id = i.id
SET i.multiple_vendors = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417309.html
標籤:
