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

mysql: how to have different order by based on field result

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

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

对于 action = a 的结果,然后按 action asc、path desc、subdomain desc、user desc 排序;

对于 action = b 的结果,然后按 action asc、subdomain asc、path asc、user desc 排序;

我需要将以上所有内容放在一个 select 声明中,即 select 基于域、子域、路径。 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 ...

提前致谢。

更新...德鲁报告这是重复的。在所引用的问题上我没有太多可以继续的,但我迈出了一大步,这是查询。查询无效(语法错误):

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;

这是可能的,但它看起来很奇怪......而且你走对了:

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 子句。