簡體   English   中英

MYSQL:使用查詢優化請求(1,n 關系)

[英]MYSQL : optimize request with query (1,n relation)

這是我的擔憂:我有一個關於兩個表的請求,在我想要優化的 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。

我的請求找到表 2 日期涵蓋的表 1 行,與 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 日期范圍內)。

有沒有辦法在不發出子請求的情況下優化這個請求?

先感謝您。

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

注意:如果時間范圍可以重疊,則需要對開始/結束子句進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM