Thursday, 30 August 2018

INNER JOIN table and returns all attached results as CSV (not separate records)

I have the following two tables with the following data. I would like to return all data when the two tables are joined. For instance, SELECT t1.data, t2.data FROM t1 INNER JOIN t2 ON t2.t1_id=t2.id WHERE t1.id=1; Now the tricky part. I don't want to return 3 rows but only one, and I would like t2.data to be CSVs. For instance, the above query would return "bla1","hi1,hi2,hi2" (if no join results, then null or "", and not ","). Is this fairly easy with just SQL, or am I better off using PHP, etc? If so with just SQL, how? Thanks

t1
-id
-data

t2
-id
-t1_id
-data

t1
-id=1, data="bla1"
-id=2, data="bla2"
-id=3, data="bla3"

t2
-id=1, t1_id=1, data=hi1
-id=2, t1_id=1, data=hi2
-id=3, t1_id=1, data=hi3
-id=4, t1_id=2, data=hi4


You can use GROUP_CONCAT which concatenates non-null values from a group using a delimiter (comma by default)
SELECT t1.data, GROUP_CONCAT(t2.data)
FROM t1 JOIN t2
 ON t1.id = t2.t1_id
WHERE t1.id = 1;

Example on SQLFiddle: http://sqlfiddle.com/#!2/68154/5

0 comments:

Post a Comment