sql - 从 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”的结果,但如果我传递任何其他值,它必须返回该行
这可能吗?
解决方案
查询可以是(具有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上的运行示例。
推荐阅读
- javascript - 如何用更多跨度标签包装html跨度标签数组?
- python-3.x - ModuleNotFoundError:没有名为“dbn”的模块
- flutter - Flutter BaseScreen 不断重建/不想要的重建
- python - 为什么 nodejs 在向端点发送 GET 请求时给我一个 403 错误,但在 python、fiddler 和 postman 中,它给了我状态 200?
- html - p-inputMask 在加载时显示黑色边框,然后在几毫秒后删除
- python - 如何使用 discord.py 打印公会的成员数
- symfony - 无法自动装配参数 $article:Symfony 5
- java - OneToMany 关系不存储实体字段
- .net - 内部联接和位置的 C# LINQ .net 核心语法问题
- mysql - 为什么我的 SELECT 查询不需要我的 UPDATE 查询需要这么长时间?