Mysql Group_concat返回重复行

时间:2013-08-02 12:20:38

标签: mysql group-concat

我有类似于Getting data from multiple tables into single row while concatenating some values的问题,但我无法理解它,我是一个新手是SQL查询。我有几个表,我必须加入它们并连续获得一些连接数据。说明如下:

Table 1 - tasks(id,title,user_id)
id     title          user_id     tree_id
--     -----          -------     -------
1      test task         1          20

Table 2 - task_follower(id,user_id,task_id)
id     user_id   task_id
--     -------   -------
1        1          1

Table 3 - account_user(id,name,email)
id      name    email
--      ----    -----
1       rakesh  kumar3180@gmail.com

Table 2 - category(id,category)
id     category
--     ------- 
1        Project1

Table 2 - task_category(id,user_id,task_id)
id     task_id   category_id
--     -------   -------
1        1          1

我运行的查询是:

    SELECT a.*, GROUP_CONCAT(b.name SEPARATOR ',') AS member_names, GROUP_CONCAT(b.email SEPARATOR ',') AS member_emails, GROUP_CONCAT(DISTINCT d.category) SEPARATOR ',') AS categories FROM tasks AS a INNER JOIN task_followers AS c ON a.id = c.task_id INNER JOIN account_user AS b ON c.user_id = b.id INNER JOIN task_category AS i ON a.id = i.task_id INNER JOIN category AS d ON i.category_id = d.id WHERE a.id = 1 AND a.user_id = 1 AND GROUP BY a.id

作为此查询的结果,我得到:

id    title       user_id   tree_id     member_names    member_emails
---   -----       -------   -------     -------------   -------------
1     test task      1        20        rakesh,rakesh   kumar3180@gmail.com,kumar3180@gmail.com

我无法理解为什么名称和电子邮件重复?请帮我解决这个问题,如果你能解释我在概念上出错的地方?

我注意到当与任务关联的类别数量多于一个时,就会出现此问题。请看http://sqlfiddle.com/#!2/b96eb/1 我在那里创建了一个例子来证明我的问题。

1 个答案:

答案 0 :(得分:1)

您可以在GROUP_CONCAT内使用DISTINCT,如下所示:

GROUP_CONCAT(DISTINCT b.email SEPARATOR ',') AS member_emails