所以我有三个包含内容的表,另一个包含这三个表的行顺序
这是表格
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 :(得分: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
答案 1 :(得分: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