sql查询一个具有自定义顺序的表

时间:2012-07-10 15:01:13

标签: sql phpmyadmin

我有一个表格,我希望在一个查询中以一些不同的条件/优先级排序。

例如,使用名为“User”的表格附带5列:

userID
userName
age
gender
birthday

如果年龄,性别和生日可能为空,我希望查询将按优先级顺序返回表行:

1. Age, gender and birthday is not null,
2. Age, gender is not null,
3. Age is not null,
4. Then the rest of the rows

我查看了UNION,UNION ALL和ORDER BY IF,但没有设法达到结果(也许我错误地查询)。

希望有人可以帮我解决这个问题。谢谢。

2 个答案:

答案 0 :(得分:3)

您的问题并不清楚每项优先事项需要满足的条件,但您可以从中得到这样的想法:

select   *
from     mytable
order by 
         case when age is null and gender is null and birthday is null then 1
              when age is null and gender is null and birthday is not null then 2
              when age is null and gender is not null and birthday is not null then 3
              when age is not null and gender is not null and birthday is not null then 4
              else 5
         end

编辑:我认为我读错了你的问题,因为缺少格式化,我把NULL与NOT NULL混在一起,但是你明白了......

答案 1 :(得分:0)

这是一个简单的订单问题:

order by (case when age is not null and birthday is not null and gender is not null then 1
               when age is not null and birthday is not null then 2
               when age is not null then 3
               else 4
          end)

您也可以在之后添加其他排序条件(例如名称或其他)。

例如,在每种情况下按年龄降序排序:

order by (case when age is not null and birthday is not null and gender is not null then 1
               when age is not null and birthday is not null then 2
               when age is not null then 3
               else 4
          end),
         age desc