如何使用SQL UNION指定订单结果?

时间:2012-05-25 07:42:44

标签: sql sql-server-2008 select sql-order-by union

我正在尝试运行以下查询:

select * from (select * from customquestionbank where questionid=6 or secondquestionid=6 
union select * from customquestionbank where questionid=5 or secondquestionid=5 
union select * from customquestionbank where questionid=10 or secondquestionid=10 
union select * from customquestionbank where questionid=11 or secondquestionid=11) Tabled

对这个网站不熟悉我还不能发布图片,但结果如下:

questionid -> 5,6 ,10,11

但是,我希望结果的显示顺序与上面的select语句相同。换句话说,questionid = 6首先返回,然后返回5,依此类推。

5 个答案:

答案 0 :(得分:2)

你不需要所有的工会,只需这样做:

SELECT DISTINCT * 
FROM   customquestionbank 
WHERE  questionid IN ( 6, 5, 10, 11 ) 
        OR secondquestionid IN ( 6, 5, 10, 11 ) 
ORDER  BY CASE 
            WHEN 6 IN ( questionid, secondquestionid ) THEN 0 
            WHEN 5 IN ( questionid, secondquestionid ) THEN 1 
            WHEN 10 IN ( questionid, secondquestionid ) THEN 2 
            WHEN 11 IN ( questionid, secondquestionid ) THEN 3 
          END 

答案 1 :(得分:0)

删除您正在使用的超级选择

将查询写为

Select * from query1 union
Select * from query2 union
Select * from query3;

这将根据需要显示您的结果

否则试试这个

Select col1,col2 from( Select 1,q1.* from query1 q1 union
Select 2,q2.* from query2 q2 union
Select 3,q1.* from query3 q3)

仅选择超级查询中所需的列

答案 2 :(得分:0)

如果您的RDBMS支持VALUES构造函数

SELECT questionid, secondquestionid
FROM   (VALUES(6,1), 
              (5, 2), 
              (10, 3), 
              (11, 4)) V(q, ord) 
       JOIN customquestionbank 
         ON q IN ( questionid, secondquestionid ) 
GROUP BY questionid, secondquestionid         
ORDER  BY MIN(ord)

答案 3 :(得分:0)

如果您的RDBMS是mysql,我认为您可以尝试这样ORDER BY FIELD

SELECT *
FROM customquestionbank
WHERE
  questionid IN(6, 5, 10, 11)
  OR secondquestionid IN(6, 5, 10, 11)
ORDER BY FIELD(questionid, 6) ASC

答案 4 :(得分:0)

Union替换为Union ALL

create table #t
(
    id int
)
insert into #t(id)values(5)
insert into #t(id)values(2)
insert into #t(id)values(4)
insert into #t(id)values(3)

Select * from
(
    Select * from #t where id = 5
    uNION All
    Select * from #t where id = 2
    uNION All
    Select * from #t where id = 4
    uNION All
    Select * from #t where id = 3
)K

DROP TABLE #t