首页 > 解决方案 > 如果值不存在,则选择空行

问题描述

我有下表:

留言

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

标签: sqlnullkeyexists

解决方案


您可以使用or

select t.*
from t
where key = ? or
      (key is null and
       not exists (select 1 from t t2 where t2.key = ?)
      );

推荐阅读