嵌套查询

Nesting queries

我对附加架构的查询要求我寻找测试呈阳性的人所在的相同位置,并且与未测试的人在同一个人中。 (未测试意味着测试中没有人 table。

--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 一个地点和参加检查和测试的人 table 结果为阳性 select 一个人 table 参加检查和测试的人测试中不存在 table.

因为我得到的答案是零,而且我手动知道有人。我做错了什么?

我希望这是有道理的。

你有几个错误(缺失存在,独立子查询存在)。我相信这应该可以完成工作

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
    )
);

您可以通过以下查询'Positive' 获得测试人员:

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)