[英]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.