SQL查询结果与唯一值相结合

时间:2013-03-06 10:37:38

标签: mysql sql join

这是我的疑问:

SELECT DISTINCT  star_user.name_user, star_group.name_group,   star_addresses.email 
FROM star_addresses

JOIN star_user_group
ON star_user_group.id_user_groupu = star_addresses.user_id

JOIN star_group
ON star_group.id_group = star_user_group.id_group_groupu

JOIN star_user
ON star_user.corespondence_user = star_addresses.id_address

JOIN star_news_group
ON star_news_group.groupid_newsg = star_user_group.id_group_groupu

WHERE newsid_newsg = 5;

运行上述查询后,我得到以下输出:

name_user|name_group|email
Zuma     |A         |abc@zz.com
Rafe     |B         |xyz@nn.com
Adam     |D         |aaa@bb.com
Zuma     |B         |abc@zz.com
Zuma     |C         |abc@zz.com

我想拥有的东西,而不是祖玛的重复价值,如她的name_user和电子邮件是这样的:

name_user|name_group|email
Zuma     |A,B,C     |abc@zz.com

那么,怎么做到这一点?非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

在MySQL中,使用GROUP_CONCAT

SELECT  star_user.name_user, 
        GROUP_CONCAT(DISTINCT star_group.name_group) name_group,   
        GROUP_CONCAT(DISTINCT star_addresses.email) email
FROM    star_addresses
        JOIN star_user_group
            ON star_user_group.id_user_groupu = star_addresses.user_id
        JOIN star_group
            ON star_group.id_group = star_user_group.id_group_groupu
        JOIN star_user
            ON star_user.corespondence_user = star_addresses.id_address
        JOIN star_news_group
            ON star_news_group.groupid_newsg = star_user_group.id_group_groupu
WHERE   newsid_newsg = 5;
GROUP   BY star_user.name_user