MySQL:使用 JOIN 和 GROUP_CONCAT 进行更新
这可能吗?
我有 2 个表,客户表和订单表。现在我想在“客户”中的一列中填写该客户的所有订单 ID(以逗号分隔)。
我尝试了类似的方法,但它不起作用:
UPDATE customers AS c
LEFT JOIN orders AS o ON o.customerid=c.customerid
SET c.orders = GROUP_CONCAT(DISTINCT o.orderid)
我得到“组函数的无效使用”。
附言。我知道最好始终在 SELECT/JOIN 中动态获取 GROUP_CONCAT 值,但我只是想知道是否可以以某种方式填充此列。
Is this possible?
I have 2 tables, Customers and Orders. Now I want to fill a column in Customers with all order id's of that customer (comma separated).
I tried something like this, but it doesnt work:
UPDATE customers AS c
LEFT JOIN orders AS o ON o.customerid=c.customerid
SET c.orders = GROUP_CONCAT(DISTINCT o.orderid)
I get 'Invalid use of group function'.
PS. I know it's better to always dynamically get the GROUP_CONCAT values in a SELECT/JOIN, but I'm just wondering if I can fill this column in some way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要在 group_concat 中添加 order by,如下例所示
注意:group_concat(version ORDER BY version SEPARATOR ',')
You will need to add an order by in the group_concat as shown in the example below
Note: group_concat(version ORDER BY version SEPARATOR ',')
这里给出的答案都不适合我,可能是因为我的情况更复杂(我需要多个连接),所以我使用了 Dennis 的解决方案,但将其拆分为一个临时表:
None of the given answers here were working for me, possibly because my case was more complicated (I needed more than one join), so I used Dennis' solution but split it into a temporary table:
基本上,您不应该以这种方式使用 GROUP_CONCAT 函数,这不是完成工作的正确方法。
在这种情况下,您可以使用嵌套查询方法,而不是尝试使用下面指定的 JOIN,尝试此查询,希望这应该可以正确完成您的工作。
尝试一次此查询,然后让我知道您是否还遇到任何问题。
湿婆
Basically you should not use the GROUP_CONCAT function in this manner, that's not the right way of making your work done.
In this scenario you can use nested queries approach instead of trying with JOINs as I specified below, try this query, hopefully this should do your work correctly.
Try this query once and then let me know if you are facing any more issues.
Siva
您忘记告诉 GROUP BY 子句。
You forget to tell the GROUP BY clause.