SQL left join和group_concat返回重复数据

时间:2014-08-14 13:08:20

标签: mysql sql left-join group-concat

我正在尝试从3个不同的表中返回2个左连接的数据。所有表都返回多行。 以下是我的发言:

"SELECT s.*, GROUP_CONCAT(sp.photo) AS photos, GROUP_CONCAT(st.name) AS tags
FROM sites s
LEFT JOIN sites_photos sp
ON sp.sites_id = s.id
LEFT JOIN sites_tags st
ON st.sites_id = s.id
WHERE s.id = 30"

此语句返回的数据如下:

Array
(
[id] => 30
[url] => www.test.be
[name] => test
[date] => 2014-08-16
[photos] => 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132191_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg, 201408141132194_gummies.jpg
[tags] => test, hello, ale, print, social, more, hcp, test, hello, ale, print, social, more, hcp
)

就像你可以看到“标签”被返回两次而“照片”被返回超过5次。当我删除一个LEFT JOIN时,查询返回正确的数据。如何防止语句返回重复数据?

提前致谢

1 个答案:

答案 0 :(得分:8)

使用

GROUP_CONCAT(DISTINCT sp.photo) AS photos, GROUP_CONCAT(DISTINCT st.name)