来自多个表的SQL select语句

时间:2020-03-30 21:53:56

标签: sql join

如果不在缺勤中的isHealty为'Y',而在missing_history中从isHealty为'N',或者在missing_history中不存在该行,我想从缺席表中获取所有行。我还想检查是否从缺勤表中的start_date过去了八个日期,而来自miss_history的isHealty为'N'或缺勤历史记录中是否不存在该行。还要使用用户类型“ A”检查缺勤情况。

PS。即使表missing_history为空,我仍然想缺席。在我的情况下,失踪表中的空表与失踪表中的isHealty ='N'相同。我的应用程序中的missing_history表仅通过夜间作业(石英)更新为新的行,并且在某些情况下,我们希望在作业运行前先缺席,因此表首先会为空。

当前结构如下:

User table
id  name   type
1   Jason  K
2   Adam   A
3   Marcus A

Absence table
id  user_id   isHealty healty_date start_date     type  
1    1        'Y'      2020-03-22  2020-03-03     Fever
2    2        'Y'      2020-03-05  2020-03-04     Sore throat
3    2        'N'      null        2020-03-03     Fever
4    3        'Y'      2020-03-05  2020-03-03     Sore throat
5    3        'Y'      2020-03-10  2020-03-07     Sore throat

Absence_history table
id  absence_id  isHealthy  date
1    1           'N'       2020-03-03
2    1           'Y'       2020-03-22
3    2           'Y'       2020-03-05
4    3           'N'       2020-03-03
5    4           'Y'       2020-03-06

我期望的结果:

id  user_id   isHealty healty_date start_date     type  
3    2        'N'      null        2020-03-03     Fever
5    3        'Y'      2020-03-10  2020-03-07     Sore throat

2 个答案:

答案 0 :(得分:0)

您可以join

select a.*
from absences a
inner join users u on u.id = a.user_id
inner join healthy h on h.absence_id = a.id
where u.type = 'A' and h.is_healthy = 'Y'

尚不清楚表absenceshealthy之间的基数是什么,因此exists也可能派上用场:

select a.*
from absences a
inner join users u on u.id = a.user_id
where 
    u.type = 'A' 
    and exists (select 1 from healthy h where h.absence_id = a.id and h.is_healthy = 'Y')

答案 1 :(得分:0)

如果要与isHealthy ='N'相对应的数据,或者健康表中不匹配的数据,则需要进行左连接。 coalesce()函数的目的是,如果isHealthy为null(不匹配),它将等于'N',因此从Absence / [User]连接中返回该行。

-- this is what your description is asking for
select a.id, a.user_id, a.type
from Absence a
inner join [User] u on a.user_id = u.id
left join Healthy h on a.id = h.absence_id
where u.type = 'A'
  and coalesce(h.isHealthy, 'N') = 'N'

更仔细地检查了您的问题和期望的结果之后,我认为您真正想要的是缺席记录,其中没有对应的isHealthy ='Y'记录。

-- this is what your results seems to be asking for
select a.id, a.user_id, a.type
from Absence a
inner join [User] u on a.user_id = u.id
where u.type = 'A'
  and not exists 
  (
    select * 
    from Healthy h
    where h.absence_id = a.id
      and h.isHealthy = 'Y'
  )

这是我的代码中的demo