这里是我的关注点:我有一个关于两个表的请求,我想对其进行优化以1,n关系。 表1是“计划”表,其中的线表示患者的过时事件。 表2是一个病人护理表,带有开始日期和结束日期。
**Table 1 : Planning**
Id
Begin
End
Patient_care_id
**Table 2 : Patient care**
Id
id_patient_care
Id patient
Begin
End
表1的每一行必须由日期至少覆盖表2的一行,但是也可以由几行2覆盖。 我无法将t1行链接到t2中的唯一ID。
我的请求在表1中找到表2的日期未包含的 行,并与table1.patient_care_id = table 2.patient_care_id链接。 要继续,我提出了一个子请求:
select id
from table1
where id not in
(
select table1.id
from table1 t1
inner join table2 t2 on t1.patient_care_id = t2.id
where t1.begin >= t2.begin and t1.end <= t2.end
)
注意:干预是在一天中进行的,t2是在计划的日期(之前在00:00:00并在23:59:59结束)不能覆盖几天,所以这就是为什么我使用t1.begin进行比较。 ..我可以使用t1.end)
示例:
T1-Planning
Id : 1
Patient_care_id : Amapa
Begin : 2020-01-01 14:00:00
End : 2020-01-01 16:00:00
Id : 2
Patient_care_id : Amapa
Begin : 2020-01-02 14:00:00
End : 2020-01-02 16:00:00
T2: Patient care
Id : 1
Patient_care : Amapa
begin : 2020-01-02 00:00:00
end : 2020-01-31 23:59:59
在这里,我希望请求从t1发送我的ID 1(不在t2日期范围内),而从T1发送Id 2(不受T2日期覆盖)。
有没有一种方法可以优化此请求而不进行子请求?
谢谢。
答案 0 :(得分:0)
SELECT t1.id
FROM Planning AS p
LEFT JOIN PatientCare AS c ON p.patient_care_id = c.id
WHERE p.begin >= c.begin
AND p.end <= c.end
AND c.id IS NULL; -- to catch rows that failed the time check
注意:如果时间范围可以重叠,则需要对begin / end子句进行更改。