sql - SQL JOIN - 在一对多关系中仅选择满足所有条件的记录
问题描述
这是一个 sybase 数据库,它遵循 t-sql 语法(与 MSSQL 相同/相似)。
我有 2 张桌子、箱子和保险。
CASES insurance
----- ---------
casenum ins_id
date_resolved
case_num
每个案例编号都有多个关联的保险条目,每个保险条目都有一个解决日期字段。
我想要做的是只返回所有相关保险条目都具有 date_resolved = null 的案例编号。
我得到的是案例编号和相关的为空的保险条目。
例如,如果一个案例编号有 3 个保险条目,其中 2 个的 date_resolved 为空,但 1在 date_resolved中有一个值,我的查询将返回案例编号,因为这 2 个条目为空。
这是我尝试过的:
select casenum
from cases
left join (select date_resolved from insurance where date_resolved is null) ins
on ins.case_num = cases.casenum
select casenum
from cases
inner join insurance on cases.casenum = insurance.case_num
where insurance.date_resolved is null
如果这是初学者的错误,我很抱歉,我搜索了董事会并发现了许多类似的问题,但似乎没有一个可以解决我的问题。
编辑 - 使用下面提供的答案之一,我将其合并到我的查询中并最终得到类似这样的东西(我相信它有效):
select casenum, *other stuff*
from cases
inner join (select i.case_num from insurance i group by i.case_num having max(date_resolved) is null) ins
on ins.case_num = cases.casenum
where *other stuff from cases table*
and *more stuff from cases table*
对此,我真的非常感激!
解决方案
一种方法是聚合:
select i.case_num
from insurance i
group by i.case_num
having max(date_resolved) is null;
或者,您可以使用not exists
:
select c.*
from cases c
where not exists (select 1
from insurance i
where i.case_num = c.case_num and i.date_resolved is not null
);
请注意,这些不是等效的。第二个返回cases
没有行的insurance
.
推荐阅读
- reactjs - 在 IIS 10 上使用 React.js 运行 .net 核心 Web 应用程序时出错
- react-native - React Native 应用程序的初始屏幕上的排毒挂起
- android - 您如何使用在类的函数中返回的 val?
- php - 用PHP提取txt中的所有行
- excel - 如何在 VBA 代码中关闭 Excel 电子表格?
- php - MYSQL PHP 选择查询的反面
- html - 如何将img的宽度和高度应用于多个div?
- python - 在 python-sell 中运行 python 脚本时出现 Python OpenCv imread 错误
- c++ - 控制台抛出;大括号初始化错误
- python - 使用 structlog 设置日志级别