将复杂的 mysql SELECT 转换为 UPDATE
我一直在尝试将复杂的 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 等(每个产品的基本信息相同)
表 products_specations:< /strong>Specifications_id,Specifications_name
Table Products_to_Specifications:Products_ID,Specifications_ID,Content
我认为对于正确的解决方案,我将使用子查询,但我不确定如何构建查询
I have been trying to convert a complex SELECT query to an UPDATE query, but I keep getting the 1064 syntax error.
The goal for the query is to update certain rows which meet particular conditions, however the joins and the GROUP BY and HAVING statements are making this impossible with the query I have now. I know this isn't the right way, but I can't discover what the solution should be. I would be great if somebody could tell me a direction for a solution!
My query (the values are not correct but give some more context):
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
My table structure:
table products: products_id, products_image, etc. (basic info same for every product)
table products_specifications: specifications_id, specifications_name
table products_to_specifications: products_id, specifications_id, content
I think for the right solution I will have use a subquery, but I'm not sure how to structure the query
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MySql 不支持 UPDATE 语句中的 GROUP BY。您可以通过将复杂查询作为派生表来轻松更新,如下所示。
希望这对您有帮助。
MySql do not support GROUP BY in UPDATE statement. You can easily update by making the complex query as a derived table as below.
Hope this helps you.