我有一个连接4个表的查询。这些表是用户,用户信息,电子邮件和电话。 用户可以拥有一个或多个电话和电子邮件。
这是SQL查询:
SELECT ur.login_id as loginId, ue.user_email_address as email, up.phone_number as phone
FROM greydeltadb.gd_user ur
LEFT JOIN greydeltadb.gd_user_info uri ON uri.user_id=ur.user_id
INNER JOIN greydeltadb.gd_user_emails ue ON ur.user_id = ue.user_id
INNER JOIN greydeltadb.gd_phone up ON ur.user_id = up.user_id
ORDER BY ur.login_id
当我执行此查询时,对于有2封电子邮件和2部电话的用户,我得到如下结果:
loginId email phone
abc abc@gmail.com 123456
abc abc@gmail.com 798446
abc def@gmail.com 123456
abc def@gmail.com 798446
然后,我了解了GROUP_CONCAT(),更新后的查询是:
SELECT ur.login_id, GROUP_CONCAT(ue.user_email_address) as emails,
GROUP_CONCAT(up.phone_number) as phones
FROM greydeltadb.gd_user ur
LEFT JOIN greydeltadb.gd_user_info uri ON uri.user_id=ur.user_id
INNER JOIN greydeltadb.gd_user_emails ue ON ur.user_id = ue.user_id
INNER JOIN greydeltadb.gd_phone up ON ur.user_id = up.user_id
GROUP BY ur.login_id
此查询返回结果:
loginId email phone
abc abc@gmail.com, def@gmail.com,abc@gmail.com, def@gmail.com 123456, 798446,123456, 798446
但我希望输出为:
loginId email phone
abc abc@gmail.com, def@gmail.com 123456, 798446
请帮助。
答案 0 :(得分:1)
只需使用DISTINCT子句,请参见GROUP_CONCAT的文档:
> GROUP_CONCAT([DISTINCT] expr [,expr ...]
> [ORDER BY {unsigned_integer | col_name | expr}
> [ASC | DESC] [,col_name ...]]
> [SEPARATOR str_val])
在MySQL中,您可以获得表达式组合的串联值。 要消除重复的值,请使用DISTINCT子句。要对结果中的值进行排序,请使用ORDER BY子句.................
在查询时,只需使用:
SELECT ur.login_id,
GROUP_CONCAT( DISTINCT ue.user_email_address ) as emails,
GROUP_CONCAT( DISTINCT up.phone_number ) as phones
.....
答案 1 :(得分:1)
您只需要一个distinct
SELECT ur.login_id,
GROUP_CONCAT(distinct ue.user_email_address) as
emails,
GROUP_CONCAT(distinct up.phone_number) as
phones
FROM greydeltadb.gd_user ur
LEFT JOIN greydeltadb.gd_user_info uri ON
uri.user_id=ur.user_id
INNER JOIN greydeltadb.gd_user_emails ue ON
ur.user_id = ue.user_id
INNER JOIN greydeltadb.gd_phone up ON ur.user_id =
up.user_id
GROUP BY ur.login_id
答案 2 :(得分:1)
首先,您没有使用One or more layouts are missing the layout_width and layout_height attributes
,因此查询中不需要它。
第二,您的uri
基本上什么也不做。我怀疑您想要用户,甚至那些没有电话或没有电子邮件的用户。如果是这样:
left join