【问题标题】:How to avoid group_concat separator duplicate in mysql select result如何避免 mysql 选择结果中的 group_concat 分隔符重复
【发布时间】:2016-01-29 03:58:58
【问题描述】:

我有 2 个表通话记录和用户,它们的字段如下

记录字段:

  • 记录ID(键)
  • 用户 ID(密钥)

用户字段:

  • 用户 ID(密钥)
  • 用户名
  • 用户备注

我想知道recordID、userName、userNote group by recordID 这是我的sql

 select record.recordID, group_concat(user.userName) as USERNAMES , group_concat(user.userNote) as USERNOTES from record 
 left outer join user on record.userID = user.USERID  
 group by record.recordID 

现在我可以用 ',' 分割 USERNAMES 和 USERNOTES 以了解每个用户名和他的用户注释

但是如果userNote中有',',可能会出错

比如BEN的userNote很好,很高,TOM的userNote很好

sql 结果将是

用户名->本,汤姆

USERNOTES->nice,tall,nice

在这种情况下,USERNOTES 将有 3 个注释,我无法区分哪一个是 TOM'S note

有什么办法可以避免这种情况吗?

或者我能做的最好的方法是使用难以出现的分隔符,例如'!@#@!'

在我的实际情况中,我有 10 个与一个键相关的表,所以如果我将所有表都外连接,将会有大量重复的行,

【问题讨论】:

  • 如果您提供一些示例数据以及您的查询返回的结果将有助于回答

标签: mysql group-by group-concat


【解决方案1】:

一种方法是不同的分隔符:

select r.recordID,
       group_concat(u.userName separator ';') as USERNAMES ,   
       group_concat(u.userNote separator ';') as USERNOTES
from record r left outer join
     user u
     on r.userID = u.USERID  
group by r.recordID ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多