任何人都可以帮我写下面的SQL吗?
假设:
tbl_request
No Title Date Priority
1 AAA 2013-08-06 3
2 BBB 2013-08-04 1
3 CCC 2013-08-05 0
4 DDD 2013-08-02 4
5 EEE 2013-08-01 2
6 FFF 2013-08-04 0
7 GGG 2013-08-03 5
8 HHH 2013-08-03 0
在sql语句中有两个要优先考虑的优先级:
我想先显示第一个优先顺序的所有请求(0不会显示)。在第一优先级之后,我想显示第二优先级。
这就是我想要的:
No Title Date Priority
2 BBB 2013-08-04 1
5 EEE 2013-08-01 2
1 AAA 2013-08-06 3
4 DDD 2013-08-02 4
7 GGG 2013-08-03 5
3 FFF 2013-08-05 0
6 GGG 2013-08-04 0
8 HHH 2013-08-03 0
我不知道如何编写sql语句来获取上面的格式。谁能告诉我怎么写呢?
提前感谢。
答案 0 :(得分:2)
像
这样的东西SELECT *
FROM Table1
ORDER BY
CASE WHEN `Priority` != 0 THEN NULL ELSE 1 END,
`Priority`,
`Date` DESC
或
SELECT *
FROM Table1
ORDER BY
CASE WHEN `Priority` != 0 THEN 0 ELSE 1 END,
`Priority`,
`Date` DESC
这将确保即使任何优先级大于其他优先级的最大值,也会将0排在最后。
答案 1 :(得分:0)
您应该使用case
表达式,如下所示
select No,Title,Date,Priority
from tab
order by
case
when Priority=0 then 9999
else Priority
end,
Date desc
答案 2 :(得分:0)
您可以尝试以下方式: -
SELECT * FROM tbl_request
WHERE Priority IN (1, 2, 3, 4, 5)
ORDER BY Priority, DATE DESC
UNION
SELECT * FROM tbl_request
WHERE Priority NOT IN (1, 2, 3, 4, 5)
ORDER BY Date DESC;
答案 3 :(得分:0)
select no,title,date,priority
from tbl_request
order by if(priority=0,99999,priority),date desc
这假设没有优先级超过99999.哟还需要在no和date列周围找回引号 - 我没有在这个键盘上使用它们!
答案 4 :(得分:0)
如果您没有显示0
优先级记录,那么下面的SQL语句就可以了。
SELECT * FROM tbl_request WHERE Priority <> 0 ORDER BY Priority ASC, Date DESC
答案 5 :(得分:0)
Select * from tbl_request
Order by ( CASE WHEN Priority > 0 THEN Priority ELSE 99999999 END ), DATE DESC
答案 6 :(得分:0)
您可以尝试:
Select title, date, priority from tbl_request Order By IF(priority = 0, 99999, priority) asc, date desc
虽然它很丑陋,效率低下,但对你有用。或者您可以考虑建立子查询的联合
Select title, date, priority from tbl_request where priority > 0 order by priority asc
union
Select title, date, priority from tbl_request where priority = 0 order by date desc
答案 7 :(得分:0)
SELECT *
FROM Table1
ORDER BY
(CASE WHEN Priority = 0 THEN 9999 ELSE 1 END) asc, date desc
答案 8 :(得分:0)
SELECT *
FROM Table1
ORDER BY field(`Priority`,0),`Priority`,
`Date` DESC
<强> FIDDLE 强>