基于不同条件检索不同行的能力



我有一个简单的两列表:

tbody> <<tr>
ProductId Value
全球1
P1232
P2343

在标量子查询上使用coalesce

select coalesce
(
(select value from t where productid = 'P123'), 
(select value from t where productid = 'Global')
) as value;

您可以筛选相应的和默认的产品,如果存在则使用ORDER和LIMIT选择相应的产品。像这样:

SELECT 
value 
FROM 
product
WHERE
ProductId='P123' OR ProductId='Global'
ORDER BY
CASE WHEN ProductId='Global' THEN 1 ELSE 0 END ASC
LIMIT
1

需要CASE子句将ID为"Global"的产品排在最后。

可以使用UNION

with data as (
select value
from product
where productid = 'P123'
)
select *
from data
union all
select value
from product
where productid = 'Global'
and not exists (select * from data);

联合的第二部分只有在第一部分没有返回任何结果时才会执行。

最新更新