一個排序的sql
按status 欄位倒序
如果status=1 time欄位正序,如果status=0 time欄位倒序
下面是需要出來的結果
id status time
5 1 50
6 1 51
1 0 99
10 0 1
回複討論(解決方案)
select * from (select * from 表 where status = 1 order by time)aunion allselect * from (select * from 表 where status = o order by time desc)b
select * from table order by status desc,if(status=1,'time asc','time desc');
order by time (case when status = 1 then desc else asc end)
select * from (select * from 表 where status = 1 order by time)aunion allselect * from (select * from 表 where status = o order by time desc)b
不行的,我試過, order要起作用,後面必須要跟limit
select * from table order by status desc,if(status=1,'time asc','time desc');
這種寫法也試過,無效的 if不能這麼用
去試了沒?
你用的什麼資料庫?
select * from table order by status desc,if(status=1,'time asc','time desc');
這種寫法也試過,無效的 if不能這麼用
select * from tbl_name order by status=1 desc, time*if(status=1,1,-1)
其中
time*if(status=1,1,-1) 將 status=0 的 time 變成負數,以適應整體的升序排列
status=1 desc 將所有 status=1 的排在最前面
order by time (case when status = 1 then desc else asc end)
這樣寫直接報錯了
改成 order by (case when status = 1 then 'time desc' else 'time asc' end)
測試不行,跟union 效果一樣
select * from tbl_name order by status=1 desc, time*if(status=1,1,-1)
其中
time*if(status=1,1,-1) 將 status=0 的 time 變成負數,以適應整體的升序排列
status=1 desc 將所有 status=1 的排在最前面
這隻適用於它這個表
order by time (case when status = 1 then desc else asc end)
這樣寫直接報錯了
改成 order by (case when status = 1 then 'time desc' else 'time asc' end)
測試不行,跟union 效果一樣
select * from table order by status=1 desc, status=0 asc 簡單粗暴實用
select * from tbl_name order by status=1 desc, time*if(status=1,1,-1)
其中
time*if(status=1,1,-1) 將 status=0 的 time 變成負數,以適應整體的升序排列
status=1 desc 將所有 status=1 的排在最前面
這隻適用於它這個表
這個有用,但IF查詢所有行進行運算再對比效率有點低了,我曾經想寫個函數(實現功能通if),後來還是決定多建個欄位,計算後按這個欄位desc
但這樣缺少靈活性,如果有其他特殊排序可能還要建欄位,然後就又把排序欄位縱向切割出來了....(針對大資料量)
order by time (case when status = 1 then desc else asc end)
這樣寫直接報錯了
改成 order by (case when status = 1 then 'time desc' else 'time asc' end)
測試不行,跟union 效果一樣
select * from table order by status=1 desc, status=0 asc 簡單粗暴實用
這句實現不了的...
select * from (select * from 表 where status = 1 order by time)aunion allselect * from (select * from 表 where status = o order by time desc)b
不行的,我試過, order要起作用,後面必須要跟limit
你是什麼資料庫?
SELECT * FROM (SELECT * FROM `table2` WHERE `status`=1 ORDER BY time ASC) aUNION ALLSELECT * FROM (SELECT * FROM `table2` WHERE `status`=0 ORDER BY time DESC) b
我在mysql 5.6上運行是OK的
select * from (select * from 表 where status = 1 order by time)aunion allselect * from (select * from 表 where status = o order by time desc)b
不行的,我試過, order要起作用,後面必須要跟limit
你是什麼資料庫?
SELECT * FROM (SELECT * FROM `table2` WHERE `status`=1 ORDER BY time ASC) aUNION ALLSELECT * FROM (SELECT * FROM `table2` WHERE `status`=0 ORDER BY time DESC) b
我在mysql 5.6上運行是OK的
mysql 5.5.24