如果我需要“排序”所有选择,如何使用联合

时间:2014-06-02 13:52:31

标签: sql

我有3个单独的选择语句,我需要联合。但是所有这些都需要通过不同的列进行排序。 我试过这个

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

但这不起作用 有没有人有这方面的经验?

3 个答案:

答案 0 :(得分:2)

您可以这样做:

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

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)

答案 1 :(得分:1)

您应该在一个公共列中分隔这些列,然后再订购

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

答案 2 :(得分:0)

你必须在UNION之后订购。

你可以"欺骗它"像这样:

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