首页 > 解决方案 > 从 SQL 查询返回不匹配的值

问题描述

表数据

| line  | exclusionflag
+-------+----------------
| aaaaa | false
| bbbbb | false
| ccccc | true
| eeeee | true
| ggggg | false
| iiiii | true

询问:

select * 
from table 
where line = 'aaaaa' AND exclusionflag = false -> works

select * 
from table 
where line = 'bbbbb' AND exclusionflag = false -> works

但是如何使以下查询工作或它的变体?

表中不存在的项目..说“ddddd”

select * 
from table 
where line = 'ddddd' AND exclusionflag = false`

现在什么都不返回,因为没有 ddddd 和 excludeflag = false 的行被理解!

但我想返回 'ccccc'、'eeeee' 和 'iiiiii' 行

换句话说,“ccccc”、“eeeee”和“iiiiii”行不包括包含“ccccc”、“eeeee”和“iiiiii”的结果,但如果我传递任何其他值,它必须返回该行

这可能吗?

标签: sqlpostgresql

解决方案


查询可以是(具有ddddd不存在的值):

with q as (select * from t where line = 'ddddd' not exclusionflag)
select * from q
union all
select * from t where exclusionflag and not exists (select * from q);

结果:

line   exclusionflag 
------ ------------- 
ccccc  true          
eeeee  true          
iiiii  true          

但是,如果您使用确实存在的值 ( bbbbb) 运行相同的查询:

with q as (select * from t where line = 'bbbbb' and not exclusionflag)
select * from q
union all
select * from t where exclusionflag and not exists (select * from q);

你得到:

line   exclusionflag 
------ ------------- 
bbbbb  false         

请参阅DB Fiddle上的运行示例。


推荐阅读