2011-04-15 63 views
5

我有2個表:SQL - MySQL的:LEFT JOIN在多行並獲取1行

表:電影

MovieID -- Name 
1   -- Movie1 
2   -- Movie2 

表:類型

MovieID -- Type 
1   -- DVD 
1   -- Bluray 
1   -- VCD 
2   -- DVD 

我需要一個查詢找出這一行: 電影1:DVD - 藍光 - VCD

我用過:

SELECT Movies.Name, 
IF(TYPE = 'DVD', 1, 0) AS DVD, 
IF(TYPE = 'Bluray', 1, 0) AS Bluray, 
IF(TYPE = 'VCD', 1, 0) AS VCD 
FROM Movies LEFT JOIN Types ON Movies.MovieID = Types.MovieID 

但它返回多盤線:

Movies.Name -- DVD -- Bluray -- VCD 
Movie1   -- 1  -- 0  -- 0 
Movie1   -- 0  -- 1  -- 0 
Movie1   -- 0  -- 0  -- 1 
Movie2   -- 1  -- 0  -- 0 

我想:

Movie1   -- 1  -- 1  -- 1 
Movie2   -- 1  -- 0  -- 0 

回答

10

group_concat()功能可能會做的伎倆,在這裏。


沒有測試,但我想這樣的事情應該工作:

SELECT Movies.Name, 
    group_concat(type separator ' - ') as type 
FROM Movies 
    LEFT JOIN Types ON Movies.MovieID = Types.MovieID 
group by Movies.Name 
+0

它的偉大工程!謝謝。 – Hamid 2011-04-15 20:23:49

+0

不客氣:-)玩得開心! – 2011-04-15 20:24:09

1

假設你想單獨列返回爲每種類型:

SELECT m.Name, 
     SUM(CASE WHEN t.Type = 'DVD' THEN 1 ELSE 0 END) AS DVD, 
     SUM(CASE WHEN t.Type = 'Bluray' THEN 1 ELSE 0 END) AS Bluray, 
     SUM(CASE WHEN t.Type = 'VCD' THEN 1 ELSE 0 END) AS VCD 
    FROM Movies m 
     LEFT JOIN Types t 
      ON m.MovieID = t.MovieID 
    GROUP BY m.Name 
0
 
SELECT m.Name, 
IF(t1.Type IS NOT NULL, 1, 0) as DVD, 
IF(t2.Type IS NOT NULL, 1, 0) as Bluray, 
IF(t3.Type IS NOT NULL, 1, 0) as VCD 
FROM Movies m 
LEFT OUTER JOIN Types t1 on m.MovieID = t1.MovieID and t1.Type = 'DVD' 
LEFT OUTER JOIN Types t2 on m.MovieID = t2.MovieID and t2.Type = 'Bluray' 
LEFT OUTER JOIN Types t3 on m.MovieID = t3.MovieID and t3.Type = 'VCD'