sql - 如果值不存在,则选择空行
问题描述
我有下表:
留言
id | key | msg
-------------------
1 | ABC | text a
2 | CDE | text c
3 | CDE | text d
4 | null | text x
如果我有,我想从表中key = X
选择所有值,或者选择所有带有 null 的值(带key = null
)。像这样的东西:
A) 消息(select ... where key = CDE
,密钥 CDE 存在)
id | key | msg
-------------------
2 | CDE | text c
3 | CDE | text d
B) 消息(select ... where key = XYZ
,键 XYZ 不存在)
id | key | msg
-------------------
4 | null | text x
解决方案
您可以使用or
:
select t.*
from t
where key = ? or
(key is null and
not exists (select 1 from t t2 where t2.key = ?)
);
推荐阅读
- android - tcp android 客户端 服务器 c linux vm
- python - 梯度计算所需的变量之一已通过就地操作进行了修改:[torch.cuda.FloatTensor [640]] 为版本 4;
- python - 将对象的函数作为参数传递给另一个函数
- android - 如何正确处理手机跨平台多登录内购服务器同步?
- android - 尝试在 Android Studio 中添加 Google Admob 时清单合并失败
- django - 管理员登录后如何重定向到另一个页面(Django)
- javascript - 有没有办法在服务器上不断运行 django 以根据实时数据更新数据库
- android - 如何在矢量图像中获得发光效果?
- javascript - 如何将跨度值传递给控制器 laravel?
- reactjs - 如何获取带有经纬度的地址?