【问题标题】:Invalid use of group function (group_concat and MySQL)组函数使用无效(group_concat 和 MySQL)
【发布时间】:2014-04-17 15:58:25
【问题描述】:

我有一个问题来实现这个:

UPDATE users
INNER JOIN relations_colors ON (relations_colors.user_id = users.id)
INNER JOIN colors ON (colors.id = relations_colors.color_id)
SET search_cache = GROUP_CONCAT( colors.name SEPARATOR " ")

phpmyadmin 说:“#1111 - 组功能使用无效”,我该如何解决?

【问题讨论】:

  • 需要更新所有用户表中的cache_search列,每个用户都有一种或多种颜色,..示例结果为:“红绿黑”

标签: mysql sql group-concat


【解决方案1】:

我认为这样的事情会执行您正在寻找的更新操作:

UPDATE users u
  JOIN ( SELECT r.user_id
              , GROUP_CONCAT(c.name SEPARATOR ' ') AS search_cache 
          FROM relations_colors r
          JOIN colors c ON c.id = r.color_id
         GROUP BY r.user_id
       ) s
    ON u.id = s.user_id
   SET u.search_cache = s.search_cache

请注意,这将仅更新 users 表中与 relations_colors/colors 匹配的行。

要更新所有用户行,您需要在 JOIN 关键字之前包含 LEFT 关键字以获得“外部联接”;对于没有任何匹配行的用户,这会将 search_cache 列设置为 NULL。

为了使结果更具确定性,我们通常会在 GROUP_CONCAT 函数中包含一个 ORDER BY 子句,例如:

GROUP_CONCAT(c.name SEPARATOR ' ' ORDER BY c.id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2018-05-14
    • 2014-03-29
    相关资源
    最近更新 更多