具有复杂排序的MySQL查询

时间:2013-11-25 16:22:23

标签: mysql

我们在MySQL中有这样的表:id - int; title - varchar;高清 - tinyint;来源 - tinyint;活跃 - tinyint;

如何通过此类排序从数据库中获取数据:

1. hd >= 3 AND source <> 5
2. hd >= 3 AND source = 5
3. hd = 2
4. other, i.e. hd < 2

请告诉我如何正确地执行此操作并进行一次SQL查询?

谢谢。

2 个答案:

答案 0 :(得分:6)

select * from your_table
order by case when hd >= 3 AND source <> 5 then 1
              when hd >= 3 AND source = 5 then 2
              when hd = 2 then 3
              else 4
         end

答案 1 :(得分:4)

试试这个:

select * 
from table_name
order by case when hd >= 3 AND source <> 5 then 1
              when hd >= 3 AND source = 5 then 2
              when hd = 2 then 3
              else 4
         end