嵌套查询

如何解决嵌套查询

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?