【问题标题】:How to implement GROUP_CONCAT [duplicate]如何实现 GROUP_CONCAT [重复]
【发布时间】:2020-12-09 09:26:12
【问题描述】:

这是我的 sql 语句

SELECT ut.*, GROUP_CONCAT(ut.bet_group_id)
FROM users_transaction AS ut
WHERE ut.user_id = 3
GROUP BY ut.user_id
ORDER BY ut.id DESC;

我的目标是group_concat bet_group_id by user_id,但是当我执行上面的查询时,我收到以下错误 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'p2p_trade.ut.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

这是我的示例表

  id   user_id   bet_group_id 
   1      3         2            
   2      3         1            
   3      3         2           
   4      3         null         

预期输出将是

  id   user_id   bet_group_id  type_id
   1      3         2,2         
   2      3         1           
   4      3         null         

【问题讨论】:

  • 您希望在这里看到的预期输出是什么?
  • 我不明白将 id 1,3 合并到 1 和 type_id 1,3 到 1 的逻辑
  • @Hirumina 我已经删除了type_id
  • @TimBiegeleisen 我已经添加了预期的输出
  • 示例表中没有deleted_at 列。

标签: mysql


【解决方案1】:

语法错误是因为GROUP BY 必须在ORDER BY 之前,尽管错误消息与您显示的不同(应该是near "GROUP BY")。

要为每个 bet_group_id 获取单独的行,您需要在 GROUP BY 子句中包含该列。

要按您想要的顺序获取行,请不要使用DESC

SELECT ut.*, GROUP_CONCAT(ut.bet_group_id)
FROM users_transaction AS ut
WHERE ut.user_id = 3
GROUP BY ut.user_id, ut.bet_group_id
ORDER BY ut.id 

DEMO

【讨论】:

猜你喜欢
  • 2011-06-01
  • 2015-07-14
  • 2018-10-30
  • 2011-12-11
  • 2012-07-14
  • 2018-04-21
  • 1970-01-01
  • 2014-11-25
  • 2013-11-21
相关资源
最近更新 更多