假设我有一个名为temp
的表,它包含int属性a
和b
:
create table temp (id int primary key, a int, b int);
insert into temp values(1, 1, 1);
insert into temp values(2, -1, 1);
insert into temp values(3, -1, -1);
我需要根据哪一个WHERE
条件成功对一些SELECT
结果进行排序。一个原始但不工作的例子:
select *, priority from temp where (
case
when a > 0 and b > 0 then 1
when a > 0 or b > 0 then 2
else 0
end
as priority
) > 0 order by priority asc
它类似于"如果a
和b
都是正的,那么这个元组将是第一个。如果至少有一个属性是正的,那么这个元组在第一个属性之后。否则不要选择
所以有可能保存CASE
结果在ORDER
中使用它吗?或者可能有解决方案,而不必在WHERE
和ORDER
中检查两次条件或制作可能昂贵的UNION
?
请解释这是什么问题(如果有的话)?
select *
from temp
order by case
when a > 0 and b > 0 then 1
when a > 0 or b > 0 then 2
else 0
end
只要用你的case,然后按子句顺序结束逻辑(不使用"priority"别名)。
这是一个演示
那么这个对你来说应该没问题:
select * --to select all
from temp --from your table
where (a > 0 or b > 0) --where a or b is bigger than 0 because this is the same as your case when then end example
order by case --I have used your logic for order by clause
when a > 0 and b > 0 then 1
when a > 0 or b > 0 then 2
else 0
end
这是第二个演示
这是OP建议的第三个选项:
select *
from temp
where (a > 0 or b > 0)
order by case
when a > 0 and b > 0 then 0
else 1
end
这是第三个演示