SQL查询 - 在Union中排序(按输入时排序)

时间:2015-10-06 23:27:45

标签: sql union

我的例子:

SELECT [thing] FROM [A]
UNION ALL
SELECT [thing] FROM [B]
UNION ALL
SELECT [thing] FROM [C]
UNION ALL
SELECT [thing] FROM [D]
UNION ALL 
SELECT [thing] FROM [E]

在我的工会中,我希望 thing 按最旧到最新的日期排序。所以,如果我今天从表A向我的事物字段添加一个值,我希望看到该值在我的联合查询中被排序到我的列的底部。有没有办法通过使用Order By来做到这一点?

1 个答案:

答案 0 :(得分:0)

select union all中表格的日期列,并将其用于order thing列。这是因为您在使用order by时无法使用union。它只能在所有查询结束时指定。

select thing from
(
SELECT [thing],[datecolumn] as dt FROM [A]
UNION ALL
SELECT [thing],[datecolumn] FROM [B]
UNION ALL
SELECT [thing],[datecolumn] FROM [C]
UNION ALL
SELECT [thing],[datecolumn] FROM [D]
UNION ALL 
SELECT [thing],[datecolumn] FROM [E]
) t
order by dt