TABLE 1
id time1 info
1 110 info1
2 120 info2
TABLE 2
id time2 info
1 100 info3
2 130 info4
我如何一次从两个表中提取数据并按时间1和时间2排序(同样的事情,但字段有不同的名称)
Expected result row ids:
1 // table 2
1 // table 1
2 // table 1
2 // table 2
答案 0 :(得分:2)
您应该使用UNION JOIN
个查询,将公共排序列(time1和time2)设为同名,并对整个重新统一的结果集进行排序。
(SELECT id, time1 AS time, info FROM table1)
UNION
(SELECT id, time2 AS time, info FROM table2)
ORDER BY time
不幸的是,这意味着无法为每个表返回不同的表结构。他们必须匹配列数等。
解决方法是这样的:
(SELECT id, time1 AS time, info, extra_column FROM table1)
UNION
(SELECT id, time2 AS time, info, NULL AS extra_column FROM table2)
ORDER BY time