2011-06-09 196 views
1

我有兩個MySQL表格,描述可以擴展到子類的數據,一個描述父類數據,另一個描述元數據字段爲一對多關係。從表使用來自連接查詢的字段值作爲列

實例行:從表

id | name 
-----+----------------------- 
123 | Example page 
999 | Another page 

實例行page_metadata

page_id | key  | value 
--------+------------+---------------- 
123  | picture | test.jpg 
123  | video  | example.avi 
123  | sound  | sound.mp3 
999  | picture | something.jpg 

問:是否有某種方式以這種形式來獲取所有數據?

id | name    | picture  | video  | sound 
-----+------------------+---------------+-------------+------------------ 
123 | Example page  | test.jpg  | example.avi | sound.mp3 
999 | Another page  | something.jpg | NULL  | NULL 
+0

查找 - 在MySQL中的數據透視表。 – Devart 2011-06-09 11:10:58

回答

1
SELECT pm.page_id as id 
    , p.name 
    , max(IF(pm.key = 'picture', pm.value, null)) as picture 
    , max(IF(pm.key = 'video', pm.value, null)) as video 
    , max(IF(pm.key = 'sound', pm.value, null)) as sound 
FROM page p 
INNER JOIN page_metadata pm ON (p.id = pm.page_id) 
GROUP BY p.id 
+0

是的,這已經足夠了。我只是將'INNER'改爲'LEFT',以包含沒有附加任何元數據的頁面。謝謝! – Kaivosukeltaja 2011-06-09 11:26:12

0

嘗試

SELECT page.id, page.name, picture.value, video.value, sound.value 
FROM page 
LEFT OUTER JOIN (SELECT page_id, value FROM page_metadata WHERE key = 'picture') as picture 
    ON page.id = picture.page_id 
LEFT OUTER JOIN (SELECT page_id, value FROM page_metadata WHERE key = 'video') as video 
    ON page.id = video.page_id 
LEFT OUTER JOIN (SELECT page_id, value FROM page_metadata WHERE key = 'sound') as sound 
    ON page.id = sound.page_id 

應該得到你所需要的

相關問題