嵌套查询

问题描述

我在所附架构中的查询要求我查找测试阳性人员去过的地方以及未测试人群所在的地方。 (未经测试意味着不在测试表中的人。

Schema

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...