首页 > 解决方案 > 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*

对此,我真的非常感激!

标签: sqljoinone-to-manysybase

解决方案


一种方法是聚合:

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.


推荐阅读