Sql 如果我需要,如何使用union;“订购”;所有选择

Sql 如果我需要,如何使用union;“订购”;所有选择,sql,Sql,我有3个单独的select语句需要合并。但它们都需要按不同的列排序。 我试过这么做 select * from( select * from (select columns from table1 order by column1 ) A UNION select * from (select columns from table2 order by column2 ) B UNION select * from (select columns from table3 order by colu

我有3个单独的select语句需要合并。但它们都需要按不同的列排序。 我试过这么做

select * from(
select * from (select columns from table1 order by column1 ) A
UNION
select * from (select columns from table2 order by column2 ) B
UNION
select * from (select columns from table3 order by column3 ) C
) Table
但这不起作用
有人对此有经验吗?

你必须在工会会议结束后订购

你可以这样“欺骗它”:

select Artificial, a,b,c from(
select 1 as Artificial, a,b,c from (select columns from table1  ) A
UNION
select 2 as Artificial,a,b,c from (select columns from table2  ) B
UNION
select 3 as Artificial,a,b,c from (select columns from table3  ) C
) derivedTable

order by Artificial, c,b,a
select *
from((select columns, 'table1' as which from table1  )
     UNION ALL
     (select columns, 'table2' from table2 )
     UNION ALL
     (select columns, 'table3' from table3 )
    ) t
order by which,
         (case when which = 'table1' then column1
               when which = 'table2' then column2
               when which = 'table3' then column3
          end);

您应该在一个公共列中分隔这些列,然后按顺序排列

SELECT * FROM
(
  SELECT A.*,columnA as ORDER_COL FROM A
  UNION ALL
  SELECT B.*,columnB as ORDER_COL FROM B
  UNION ALL
  SELECT C.*,columnC as ORDER_COL FROM C
) as T1 
ORDER BY ORDER_COL

您可以这样做:

select Artificial, a,b,c from(
select 1 as Artificial, a,b,c from (select columns from table1  ) A
UNION
select 2 as Artificial,a,b,c from (select columns from table2  ) B
UNION
select 3 as Artificial,a,b,c from (select columns from table3  ) C
) derivedTable

order by Artificial, c,b,a
select *
from((select columns, 'table1' as which from table1  )
     UNION ALL
     (select columns, 'table2' from table2 )
     UNION ALL
     (select columns, 'table3' from table3 )
    ) t
order by which,
         (case when which = 'table1' then column1
               when which = 'table2' then column2
               when which = 'table3' then column3
          end);
这假设用于排序的列都是相同类型的

请注意,此查询使用
union all
而不是
union
。如果希望三个子查询的结果独立排序,我看不出有什么理由要消除重复项

编辑:

您还可以通过分别表示每个表的
顺序:

order by which,
         (case when which = 'table1' then column1 end) ASC,
         (case when which = 'table2' then column2 end) DESC
         (case when which = 'table3' then column3 end)

它们有相同的结构吗?不清楚你到底在问什么。您是否可以提供一个示例,说明您获得的数据和您想要的结果,以澄清问题?这些查询具有相同的结构。我从相同的表格中进行选择。但是它们有不同的条件,需要由不同的专栏来订购。这似乎是可行的。非常感谢。但我还需要添加asc和desc。使用此方法是否可能?如何将asc和desc添加到此中?