【问题标题】:MySQL statement for group_concat in Update from two other tables来自其他两个表的更新中 group_concat 的 MySQL 语句
【发布时间】:2020-08-24 15:39:16
【问题描述】:

我在下面有 3 个表我正在尝试为表 cart_session 中的“item”列编写 group_concat 语句

products

id      name
------------------------
123  |  car
456  |  boat
789  |  house

--------------------------------

cart_items

pid session
----------------------
123  |  ABCD    
456  |  ABCD
789  |  EFGH

----------------------------------

cart_session

id   item
----------------------------
ABCD  |  car,boat
EFGH  |  house

【问题讨论】:

  • 不要这样做。见规范化。

标签: mysql sql join group-by sql-update


【解决方案1】:

您可以按如下方式使用更新/加入语法:

update cart_session cs
inner join (
    select ci.session, group_concat(p.name) item
    from products p
    inner join cart_items ci on ci.pid = p.pid
    group by ci.session
) x on x.session = cs.session
set cs.item = x.item

另一个选项使用相关子查询:

update cart_session cs
set cs.item = (
    select group_concat(p.name)
    from products p
    inner join cart_items ci on ci.pid = p.pid
    where ci.session = cs.session
)

这略有不同:此查询会将 null 值分配给 cart_session 中在其他表中没有匹配的行,而第一个查询将保留这些行不变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多