mysql:如何根据字段结果得到不同的顺序

时间:2016-09-27 20:25:02

标签: mysql sql-order-by

我有一个域,子域,路径,操作,类型,用户表,我根据操作字段对结果进行排序。

type表示记录的类型(2 =域,3 =子域,4 =路径)。

for action with action = a then order by action asc,path desc,subdomain desc,user desc;

for action = b然后按行动命令asc,subdomain asc,path asc,user desc;

我需要以上所有内容在一个基于域,子域,路径选择的select语句中。选择将从以下开始:

select action, user 
from table1 
where (domain = 'testdomain.com' and type = 2) 
or (domain = 'testdomain.com' and subdomain = 'sub1'and type = 3) 
or (domain = 'testdomain.com' and path = 'path1' and type = 4) 
and (user is null or user = 'smith') 
order by ...

提前致谢。

更新...... Drew报告此重复。在引用的问题中,我没有太多的东西可以继续,但我采取了飞跃,这是查询。查询不起作用(语法错误):

select action, type, user from filterList 
where (domain = 'testdomain.com' and type = 2) 
or (domain = 'testdomain.com' and subdomain = 'sub1' and type = 3) 
or (domain = 'testdomain.com' and path = 'path1' and type = 4) 
and (user is null or user = 'smith') 
order by `action` asc, 
CASE `action` 
WHEN 'a' THEN order by path desc, subdomain desc, user desc 
WHEN 'b' THEN order by subdomain asc, path asc, user desc;

1 个答案:

答案 0 :(得分:1)

这是可能的,但它看起来很奇怪......你走在正确的轨道上:

order by `action` asc, 
CASE `action` WHEN 'a' THEN path ELSE NULL END DESC,
CASE `action` WHEN 'a' THEN subdomain ELSE NULL END DESC,
CASE `action` WHEN 'a' THEN user ELSE NULL END DESC,
CASE `action` WHEN 'b' THEN subdomain ELSE NULL END ASC,
CASE `action` WHEN 'b' THEN path ELSE NULL END ASC,
CASE `action` WHEN 'b' THEN user ELSE NULL END DESC

我猜你得到的语法错误是因为你不能在CASE语句中放置ORDER BY子句。