[英]select the records only if ALL related records match
我再次被一个查询困住了。 我想从 table1 中选择所有相关 table2 记录满足条件的所有记录。 只有当 ALL 表 2 记录满足它时。
我试过这个。 但它不起作用。
select m.* from table1 m
inner join table2 I on m.Id = I.Id
where
I.Id = ALL (select t.Id from table2 t where t.Id = I.Id and t.Status = 3)
如果您想要m
中所有状态为3
的行I
,则使用not exists
:
select m.*
from table1 m
where not exists (select 1
from table2 I
where I.Id = m.Id and I.status <> 3
);
编辑:
请注意,这会匹配table2
中没有匹配项的行。 这在技术上满足所有行的状态为3
。 但是如果你想要求一行,你可以添加一个exists
条件:
select m.*
from table1 m
where not exists (select 1
from table2 I
where I.Id = m.Id and I.status <> 3
) and
exists (select 1
from table2 I
where I.Id = m.Id and I.status = 3
);
这两者都可以利用table2(Id, status)
上的索引。 使用某种形式的聚合的方法需要额外的工作,并且在大型数据集上的性能应该会table2
一些(特别是当table2
有很多匹配项时)。
您可以删除与 table2 的连接并将全部更改为 in 或exists。 或者您可以将 t.status = 3 添加到 on 子句并摆脱 where 子句。
您可以将NOT EXISTS
添加到ON
子句:
select m.*
from table1 m inner join table2 I
on m.Id = I.Id
and not exists (select t.Id from table2 t where t.Id = m.Id and t.Status <> 3)
这样您就可以从table1
选择与table2
相关的所有行,并且相关行都满足Status = 3
的条件。
或者,在没有join
,在WHERE
子句中使用返回满足条件Status = 3
的table2
所有Id
的子查询:
select *
from table1
where Id in (
select Id from table2
group by Id
having min(Status) = 3 and max(Status) = 3
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.