access-SQL-Query - 在 UNION ALL 中使用 "Order By"

access-SQL-Query - Using "Order By" in UNION ALL

我在 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

我哪里做错了?

试试这个:

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;

不要在 select 上使用 select * from。像下面这样使用

SELECT table1.name , table1.age FROM table1 ORDER BY table1.age 
union all
SELECT table2.name , table2.age FROM table2 ORDER BY table2.age
union all
SELECT table3.name , table3.age FROM table3 ORDER BY table3.age