Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL left join and group_concat returns duplicate data

I am trying to return data from 3 different tables with 2 left joins. All tables return multiple rows. Here is my statement:

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

The data this statement returns looks like:

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
)

Like you can see "tags" are returned twice and the "photos" more than 5 times. When I remove one LEFT JOIN the query returns the right data. How can prevent the statement from returning duplicate data?

Thanks in advance.

like image 616
user2381011 Avatar asked Aug 14 '14 13:08

user2381011


1 Answers

Use

GROUP_CONCAT(DISTINCT sp.photo) AS photos, GROUP_CONCAT(DISTINCT st.name)
like image 194
kayra Avatar answered Oct 10 '22 03:10

kayra