首页 > 解决方案 > where 子句中每个键的默认值

问题描述

给定一张桌子:

ID VALUE
1  1
2  2

我需要为 where-clause 中的每个 ID 以及 ID 设置 0:

select ... where ID in(1,2,3,4) ...

结果

ID VALUE
1  1
2  2
3  0
4  0

我可以在这里使用什么查询?

Upd1:让它成为 Postgres。

Upd2:我可以不加入吗?

标签: sqlpostgresql

解决方案


您没有提到您的 DBMS,但以下是标准 ANSI SQL:

select l.id, coalesce(t.value, 0) as value
from (
  values (1),(2),(3),(4)
) as l(id)
  left join the_table t on t.id = l.id;

没有连接是可能的,但这并不能使它更漂亮:

with input(id) as (
  values (1),(2),(3),(4)
)
select *
from the_table 
where id in (select id from input)
union all
select id, 0
from input
where id not in (select id from the_table)

推荐阅读