I have two MySQL tables describing data that can be extended into subclasses, one that describes the parent class data and another one describing metadata fields as one-to-many relationships.
Example rows from table page:
id | name
-----+-----------------------
123 | Example page
999 | Another page
Example rows from table page_metadata:
page_id | key | value
--------+------------+----------------
123 | picture | test.jpg
123 | video | example.avi
123 | sound | sound.mp3
999 | picture开发者_JAVA百科 | something.jpg
Question: Is there some way to fetch all this data in this format?
id | name | picture | video | sound
-----+------------------+---------------+-------------+------------------
123 | Example page | test.jpg | example.avi | sound.mp3
999 | Another page | something.jpg | NULL | NULL
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
Try
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
should get what you need
精彩评论