2016-09-15 94 views
0

我有這兩個表。我會讓它儘可能簡單:MySQL一對多關係單查詢

Sample value in main_table: 
id = 1 

Sample value in details_table: 
id = 1 
type = book 
name = harry potter 

id = 1 
type = paper 
name = post it 

我需要的結果是獲得ID的名稱爲這兩種類型。

id book   paper 
1  harry potter post it 

這是可能的嗎?

回答

1

你期望的輸出會暗示你想要以轉動type和基於它的值列。假設可出現的唯一類型bookpaper,然後下面的查詢應該工作:

SELECT t2.id, 
     MAX(CASE WHEN t2.type = 'book' THEN name ELSE NULL END) AS book, 
     MAX(CASE WHEN t2.type = 'paper' THEN name ELSE NULL END) AS paper 
FROM main_table t1 
INNER JOIN details_table t2 
    ON t1.id = t2.id 
GROUP BY t2.id 

演示在這裏:

SQLFiddle

+0

什麼是MAX? – aozora

+0

@aozora這是一個數據透視查詢,'MAX'將保留每個透視列的非NULL值。 –

+0

謝謝,我不知道我在做什麼的正確名詞。現在我知道這是關鍵。 – aozora

2

只需加入細節表兩次:

Select m.id, d1.name as book, d2.name as paper from main_table m 
join Details_table d1 on m.id =d1.id and d1.type = 'book' 
join Details_table d2 on m.id =d2.id and d2.type = 'paper' 
+0

尼斯的答案了。但我喜歡加入一次。我不知道這是否會影響更大查詢的性能。還是一個很好的回答 – aozora