我现在要写一条查询的SQL语句,试了很长时间还是没写出来,现求各位帮忙了~
假设有如下表格t_context,其中type共有A、B、C种类型,优先级依次为B>A>C,现在要查询该表格中的所有数据,不过须按如下规则排序:
1、类型为B的排在第一,若有多条则按时间递减;
2、类型为A的排在第二,若有多条则按时间递减;
3、剩下的则按时间递减即可。
id | type | date | context |
1 | C | xxxx-xx-xx xx:xx:xx | ... |
2 | C | xxxx-xx-xx xx:xx:xx | ... |
3 | A | xxxx-xx-xx xx:xx:xx | ... |
4 | C | xxxx-xx-xx xx:xx:xx | ... |
5 | B | xxxx-xx-xx xx:xx:xx | ... |
6 | A | xxxx-xx-xx xx:xx:xx | ... |
怎样用一条select语句实现这种规则的排序结果?
mysql实现:
[code="sql"]select id,type,date,context from (
select id,
(case type when 'A' then 2 when 'B' then 3 else 1 end) level,
type,
date,
context
from t_context
) t
order by t.level desc,t.date desc;[/code]
oracle的话,可以把case部分用decode代替
其实主要还是你们设计有问题,如果优先级这样设计:
优先级依次为A>B>C这样在效率上要高很多
如果优先级大小无法调整,可以用case when 或者union