我有一个包含域、子域、路径、操作、类型、用户的表,我可以根据操作字段对结果进行排序。
type 表示记录类型(2 = 域、3 = 子域、4 = 路径)。
对于 action = a 的结果,然后按操作 asc、路径 desc、子域 desc、用户 desc 排序;
和
对于action = b的结果,然后按操作asc、子域asc、路径asc、用户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 ...
提前致谢。
更新...德鲁将此报告为重复。在所引用的问题中,我没有太多可说的,但我迈出了一步,这是查询。查询不起作用(语法错误):
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 子句。
关于mysql:如何根据字段结果有不同的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733685/