Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating rows in relation to a JOIN

Suppose I have a cooking show:

cookingepisodes
id | date
---------------
1  | A
2  | B
3  | C
4  | D
…

This show reviews products in these categories (left) and are linked by the table to the right:

tests               testitems
id | name           id | episodeid | testid | name
------------        ------------------------------------
1  | cutlery        1  | 1         | 1      | Forks
2  | spices         2  | 2         | 1      | Knives
                    3  | 4         | 1      | Spoons
                    4  | 4         | 2      | Oregano

My desired output is this:

showid | testid | testname
     4 | 1,2    | cutlery, spices
     3 | NULL   | NULL
     2 | 1      | cutlery
     1 | 1      | cutlery

I've tried using this query, and it works as long as I don't need to concatenate the results (when there are two tests on the same episode). Then the join will create multiple rows based on the number of

SELECT DISTINCT e.*, i.testid, t.name AS testname
FROM cookingepisodes AS e
LEFT OUTER JOIN testitems AS i ON i.episodeid = e.id
LEFT OUTER JOIN tests AS t ON i.testid = t.id
ORDER BY e.date DESC

I've also tried something like this, but I can't get it to work because of the outer block reference (e.id):

JOIN (
  SELECT GROUP_CONCAT(DISTINCT testid) 
  FROM testitems 
  WHERE testitems.episodeid = e.id
) AS i

Any tips on how I can solve this without restructuring the database?

like image 269
ehm Avatar asked Jan 09 '12 12:01

ehm


1 Answers

Try this one -

SELECT
  ce.id showid,
  GROUP_CONCAT(te.testid) testid,
  GROUP_CONCAT(t.name) testname
FROM cookingepisodes ce
  LEFT JOIN testitems te
    ON te.episodeid = ce.id
  LEFT JOIN tests t
    ON t.id = te.testid
GROUP BY
  ce.id DESC;
like image 125
Devart Avatar answered Sep 22 '22 14:09

Devart