我需要将两个子选择组合成一个可排序的结果。数据来自同一服务器上的两个数据库。
例如,我有这两个问题:
查询#1
SELECT bar.that_id AS id, bar.object_title AS title, bar.timestamp AS timestamp, 'db2' as db
FROM `db2`.`bar` AS `bar`
ORDER BY bar.timestamp DESC
查询#2
{{1}}
现在我想以某种方式将这两个选择连接到一个结果中,并使用LIMIT和偏移来对结果进行分页。
这甚至可能吗? 加入两个子选择没有表格。
答案 0 :(得分:1)
尝试使用UNION ALL
这个:
(
SELECT foo.someId AS id, foo.name AS title, foo.tstmp AS timestamp, 'db1' as db
FROM `db1`.`table_foo` AS `foo`
) UNION All (
SELECT bar.that_id AS id, bar.object_title AS title, bar.timestamp AS timestamp, 'db2' as db
FROM `db2`.`bar` AS `bar`
)
ORDER BY 3 DESC
LIMIT N,M
如果没有可选的ALL
,则会删除重复的条目。如果你可以统治我的副本,你可能不需要它。