我一直在尝试将复杂的SELECT查询转换为UPDATE查询,但我不断收到1064语法错误。
查询的目标是更新满足特定条件的某些行,但是连接和GROUP BY和HAVING语句使我现在的查询无法实现。我知道这不是正确的方法,但我无法发现解决方案应该是什么。如果有人能告诉我解决方案的方向,我会很棒!
我的查询(值不正确,但提供更多上下文):
UPDATE products p
JOIN products_to_specifications pts ON pts.products_id = p.products_id
JOIN products_specifications ps ON ps.specifications_id = pts.specifications_id
SET p.products_image = 'file_name.jpg'
WHERE ps.specifications_name IN ('color')
AND pts.content IN ('black')
AND p.products_manufacturer = 'BMW'
AND p.products_name = 'M5'
GROUP BY p.products_id
HAVING COUNT(DISTINCT ps.specifications_name) = 1 AND COUNT(DISTINCT pts.content) = 1
我的表结构:
表产品: products_id,products_image等(每种产品的基本信息相同)
table products_specifications: specifications_id,specifications_name
表products_to_specifications: products_id,specifications_id,content
我认为对于正确的解决方案,我将使用子查询,但我不确定如何构造查询
答案 0 :(得分:0)
MySql在UPDATE语句中不支持GROUP BY。您可以通过将复杂查询作为派生表轻松更新,如下所示。
UPDATE products p, (SELECT p.products_id FROM products p
JOIN products_to_specifications pts ON pts.products_id = p.products_id
JOIN products_specifications ps ON ps.specifications_id = pts.specifications_id
WHERE ps.specifications_name IN ('color')
AND pts.content IN ('black')
AND p.products_manufacturer = 'BMW'
AND p.products_name = 'M5'
GROUP BY p.products_id
HAVING COUNT(DISTINCT ps.specifications_name) = 1 AND COUNT(DISTINCT pts.content) = 1) AS t
SET p.products_image = 'file_name.jpg' WHERE p.products_id=t.products_id
希望这会对你有所帮助。