2011-05-17 102 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