MYSQL:使用查询优化请求(1,n关系)

问题描述 投票:-1回答:1

[这里是我的关注点:我有一个关于两个表的请求,我想对其进行优化以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 =表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日期涵盖)。

是否有一种方法可以优化此请求而不进行子请求?

先谢谢您。

mysql optimization request
1个回答
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

注意:如果时间范围可以overlap,则需要对begin / end子句进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.