我在Microsoft Access 2016中尝试了这个SQL查询
SELECT * FROM (
SELECT table1.name , table1.age FROM table1 ORDER BY table1.age
)
union all
SELECT * FROM (
SELECT table2.name , table2.age FROM table2 ORDER BY table2.age
)
union all
SELECT * FROM (
SELECT table3.name , table3.age FROM table3 ORDER BY table3.age
);
我在a similar question找到但是它对我不起作用,这是我的结果:
name age
aa 100
bb 66
cc 200
dd 78
tt 38
gg 77
这是我的表的顺序,我想要的结果是这样的 : -
name age
bb 66
aa 100
dd 78
cc 200
tt 38
gg 77
我哪里做错了?
答案 0 :(得分:1)
试试这个:
SELECT table1.name, table1.age FROM table1
UNION ALL
SELECT table2.name, table2.age FROM table2
UNION ALL
SELECT table3.name, table3.age FROM table3
ORDER BY 2;
您正在从子查询中排序结果,然后将这些结果一起加入无序列表中。您需要将ORDER BY移动到查询的末尾。
正如Damien所说,您需要在查询结束时进行ORDER BY,否则您无法保证结果始终是您想要的结果。这样的事情应该可以胜任:
SELECT name, age FROM (
SELECT 1 AS table_order, table1.name, table1.age FROM table1
UNION ALL
SELECT 2 AS table_order, table2.name, table2.age FROM table2
UNION ALL
SELECT 3 AS table_order, table3.name, table3.age FROM table3
) x
ORDER BY table_order, age;
答案 1 :(得分:0)
请勿在{{1}}之上使用select * from
。使用如下
select