sql - 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:我可以不加入吗?
解决方案
您没有提到您的 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)
推荐阅读
- python - 使用 Python 和 Beautifulsoup 抓取 ASOS 产品价格的网页
- image-processing - 缩小比例时双线性插值如何工作?
- c++ - 全局静态对象销毁后是否可以调用 OS 计时器回调?
- python - 完成文件中的 URL 列表循环时未提供架构
- html - html表格输入数据输入txt文件
- python - 如何检查两个变量是否引用同一个熊猫对象?
- php - 在laravel的where条件下使用数组
- css - BUG - iOS 设备上的 CSS 媒体查询
- python - 如何在同一个文本输入框中实现实时降价预览?
- tensorflow - 为什么我们需要多放一层,softmax 激活函数在哪里?