您好,欢迎访问一九零五行业门户网

这样的需求sql怎么写?

一个排序的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
其它类似信息

推荐信息