如何解决嵌套查询
我在所附架构中的查询要求我查找测试阳性人员去过的地方以及未测试人群所在的地方。 (未经测试意味着不在测试表中的人。
--find the same locations of where the positive people and the untested people went
select checkin.LociD,checkin.PersonID
from checkin join testing on checkin.personid = testing.personid
where results = 'Positive'
and (select CheckIn.PersonID
from checkin join testing on checkin.PersonID = testing.PersonID where CheckIn.PersonID
not in (select testing.PersonID from testing));
要从检查和测试表中选择一个位置和人员,结果是肯定的,并从检入表中选择一个不在测试表中的人员。
由于我得到的答案是零,所以我手动知道有人。我在做什么错了?
我希望这是有道理的。
解决方法
您可以通过以下查询让测试过的人“积极”:
select personid from testing where results = 'Positive'
以及未经测试的人:
select p.personid
from person p left join testing t
on t.personid = p.personid
where t.testingid is null
您必须将checkin
的副本加入每个查询中,并且这些副本也必须结合在一起:
select l.*
from (select personid from testing where results = 'Positive') p
inner join checkin cp on cp.personid = p.personid
inner join checkin cu on cu.lid = cp.lid
inner join (
select p.personid
from person p left join testing t
on t.personid = p.personid
where t.testingid is null
) pu on pu.personid = cu.personid
inner join location l on l.locationid = cu.lid
,
如果您想要的是阳性的人,而他们所在的地方也有未经测试的人,则可以考虑:
select ch.LocID,group_concat(case when t.results = 'positive' then ch.PersonID end) as positive_persons
from checkin ch left join
testing t
on ch.personid = t.personid
group by ch.LocId
having sum(case when t.results = 'positive' then 1 else 0 end) > 0 and
count(*) <> count(t.personid); -- at least one person not tested
通过这种结构,您可以使用以下方法来获得未经测试的人员:
group_concat(case when t.personid is null then ch.personid)
,
您有几个错误(缺少存在,存在独立的子查询)。我相信这应该可以完成工作
select ch1.LocID,ch1.PersonID
from checkin ch1
join testing t1 on ch1.personid = t1.personid
where results = 'Positive'
and exists (
select 1
from checkin ch2
where ch1.LocID = ch2.LocID and ch2.PersonID not in (
select testing.PersonID
from testing
)
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。