2011-05-17 101 views
1

持有這些條目的順序選擇行,所以我必須與持有這三個表如何從基於四表三個表之一,從所有三個表

這裏是排順序的內容和一個三個表表

table content_order 
id | content_type | content id 
1 | content1 | 1 
2 | content1 | 2 
3 | content3 | 1 
4 | content2 | 1 

table content1 
id | some_text 
1 | aaaa 
2 | bbb 

table content2 
id | some_text 
1 | text yyyy 

table content3 
id | some_text 
1 | text bbbb 

那麼我該如何得到這個?

content_type | some_text | content_id 
content1 | aaaa | 1 | 
content2 | bbb | 2 | 
content3 | yyyy | 1 | 
content2 | bbbb | 1 | 
+0

看起來你的結果有一個錯字。第二行不應該是content1嗎? – Hogan 2011-05-17 10:38:29

回答

0

試試這個:

SELECT content_type, some_text, id as content_id 
FROM (
       SELECT 'content1' as content_type, content1.Id, content1.some_text 
    UNION ALL SELECT 'content2', content2.Id, content2.some_text 
    UNION ALL SELECT 'content3', content3.Id, content3.some_text) contents 
JOIN content_order 
    ON content_order.content_type = contents.content_type 
AND content_order.content_Id = contents.Id 
ORDER BY content_order.id 
+0

他希望它按content_order.id – Hogan 2011-05-17 10:47:48

1

這將在T-SQL工作,有可能是MySQL的細微差別。

select co.content_type, 
     coalesce(c1.some_text,c2.some_text,c3.some_text) as some_text, 
     coalesce(c1.id,c2.id,c3.id) as content_id 
from content_order co 
left join content1 c1 on co.content_id = c1.id and co.content_type = 'content1' 
left join content2 c2 on co.content_id = c2.id and co.content_type = 'content2' 
left join content3 c3 on co.content_id = c3.id and co.content_type = 'content3' 
order by co.id 
+0

這是好的,但答案更好,因爲我沒有在所有三個表中所有相同的行 – luka 2011-05-17 11:42:40

+0

@luka - 如果你瞭解SQL,你會知道行數在3個內容表上並不重要,我的解決方案明顯更快。 – Hogan 2011-05-17 13:13:33