[英]Checking for an overlap and if values are already taken
我正在嘗試編寫一個 SQL 查詢,該查詢必須檢查兩個小時之間是否存在重疊以及是否已經選擇了某些值。 例如,您在表格中有一條記錄,您需要用數據填寫表格。 使用 SQL 查詢,您需要檢查表中的小時數與您在表單中選擇的小時數之間是否存在重疊,但您還需要檢查表單中選擇的其他數據是否尚未在比較表中使用與表中的另一個數據。 我的問題是檢查表中是否已經存在值,因此我可以返回一個錯誤,說明這些數據已被使用。 需要明確的是,您有那些需要驗證的數據。 你有時間、房間、老師和課程。 您必須檢查是否檢測到與時間重疊(這部分我沒有問題),但您還需要檢查老師是否已經在某個房間教授某門課程(您不能讓老師在兩個不同的地方),如果一個房間還沒有被占用,也如果一個課程還沒有被占用。 我實際上有這個 SQL 查詢,但它不是一個正確的查詢,因為當我用兩個小時(例如:08:00 和 12:00)進行插入時,一個老師(例如:老師 A),一個房間(例如:房間 A)和一門課程(例如:課程A),沒有問題,因為它是表中的第一個插入。 但是當我在不換老師的情況下換房間(A房間到B房間)檢查是否會返回錯誤(因為老師不能同時在兩個不同的地方),沒有錯誤,插入是在表中制作。 我會給你我的 SQL 查詢:
select * from `reservations`
where heure_debut <= '08:00' and heure_fin >= '08:00'
and heure_debut <= '09:00' and heure_fin >= '09:00'
and reservations.local_id = 1
and exists
(select * from `reservations` where reservations.enseignant_id = 1)
and exists
(select * from `reservations` where reservations.Event_id = 1)
我試圖了解我失敗的地方,但我不知道在哪里。 預先感謝您的回答。
我認為你采取了錯誤的方式,對我來說這是一個負面檢查,如果它給你帶來超過 0 行,那將失敗:
如您所見,我在您的查詢中找不到OR
。 (我沒有給你Event_id
的東西,所以我可能會錯過這里的東西)
這是可以回答至少大部分問題的部分,告訴我什么仍然不適合你。
查詢 1 :
SET -- this is your input you try to check
@local_id = 1,
@heure_debut = '08:00',
@heure_fin = '09:00',
@enseignant_id = 1
結果:
查詢 2 :
-- if it return more that 0 record, then you have a conflict
SELECT
r.id AS id_line_in_conflict
, r.* -- for debug
FROM `reservations` r
WHERE
heure_debut < @heure_fin
AND heure_fin > @heure_debut
AND (
local_id = @local_id -- check if the local is empty
OR enseignant_id = @enseignant_id -- check if the teacher is free
)
結果:
| id_line_in_conflict | id | numero_semaine | date | heure_debut | heure_fin | Event_id | horaire_id | local_id | enseignant_id |
|---------------------|----|----------------|----------------------|-------------|-----------|----------|------------|----------|---------------|
| 1 | 1 | 16 | 2020-04-17T00:00:00Z | 08:00 | 12:00 | 1 | 4 | 1 | 1 |
| 2 | 2 | 16 | 2020-04-17T00:00:00Z | 08:00 | 09:00 | 1 | 4 | 2 | 1 |
查詢 3 :
SET -- this is your input you try to check
@local_id = 1,
@heure_debut = '14:00',
@heure_fin = '15:00',
@enseignant_id = 3
結果:
問題 4 :
-- if it return more that 0 record, then you have a conflict
SELECT
r.id AS id_line_in_conflict
, r.* -- for debug
FROM `reservations` r
WHERE
heure_debut < @heure_fin
AND heure_fin > @heure_debut
AND (
local_id = @local_id -- check if the local is empty
OR enseignant_id = @enseignant_id -- check if the teacher is free
)
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.