我有一个简单的两列表:
ProductId | Value | 全球 | 1 |
---|---|
P123 | 2 |
P234 | 3 |
在标量子查询上使用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);
联合的第二部分只有在第一部分没有返回任何结果时才会执行。