连接与JOIN相关的行

时间:2012-01-09 12:19:54

标签: mysql concatenation

假设我有一个烹饪节目:

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

此节目回顾了这些类别中的产品(左),并通过右侧表格链接:

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

我想要的输出是:

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

我已尝试使用此查询,只要我不需要连接结果(当同一集中有两个测试时)它就可以工作。然后,连接将根据

的数量创建多个行
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

我也尝试过类似的东西,但由于外部块引用(e.id),我无法使它工作:

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

关于如何在不重组数据库的情况下解决这个问题的任何提示?

1 个答案:

答案 0 :(得分:9)

试试这个 -

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;