2

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

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

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

4

5 回答 5

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 
于 2012-05-25T07:55:07.473 回答
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)

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

于 2012-05-25T07:53:33.790 回答
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)
于 2012-05-25T08:00:13.673 回答
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
于 2012-05-25T08:04:52.940 回答
0

替换UnionUnion 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
于 2012-05-25T10:09:53.327 回答