我 想要任何类型的JOIN
。我正在使用PHP构建两个表的RSS提要,我想从两个表中选择所有行,保持行分开但按常用created
列排序。
例如,如果我有一个表foo
:
id downloads views created
-----------------------------------------------
1 12 23 2011-07-22 00:10:16
2 51 900 2011-07-22 10:11:45
3 8 80 2011-07-23 04:12:18
表格bar
:
id title body created
-----------------------------------------------
1 foo ogblog 2011-07-21 10:54:07
3 bar zip 2011-07-24 10:54:07
4 zip bar 2011-07-25 10:54:07
我想从通用created
列排序的两个表中选择所有数据,因此示例结果集将是(忽略bar.id
,因为它不需要):< / p>
id title body downloads views created | table
-------------------------------------------------------------------------------
NULL bar zip NULL NULL 2011-07-24 10:54:07 | bar
NULL foo ogblog NULL NULL 2011-07-21 10:54:07 | bar
1 NULL NULL 12 23 2011-07-22 00:10:16 | foo
2 NULL NULL 51 900 2011-07-22 10:11:45 | foo
3 NULL NULL 8 80 2011-07-23 04:12:18 | foo
NULL zip bar NULL NULL 2011-07-25 10:54:07 | bar
不需要table
列;我添加它是为了让事情更容易理解。
希望很明显我想做什么;而不是从两个表中的列生成行JOIN
,我希望获得具有公共列布局的所有行数据,其中表中不存在的任何列都具有NULL
投入其中。
如果您需要澄清,请告诉我。
答案 0 :(得分:30)
使用虚拟列来计算不同的结构,使用联合来加入它们,使用父选择来处理排序:
SELECT * FROM (
(SELECT foo.id, NULL AS title, NULL AS body, foo.downloads, foo.views, foo.created FROM foo)
UNION ALL
(SELECT NULL AS id, bar.title, bar.body, NULL AS downloads, NULL AS views, bar.created FROM bar)
) results
ORDER BY created ASC
答案 1 :(得分:14)
扩展@Brendan Bullen的建议,这是一个使用UNION ALL
的示例,它应该适合您:
SELECT id as id, NULL as title, NULL as body, downloads as downloads,
views as views, created as created, 'foo' as table_name
FROM foo
UNION ALL
SELECT NULL as id, title as title, body as body, NULL as downloads,
NULL as views, created as created, 'bar' as table_name
FROM bar
ORDER BY created ASC