大家好,我有以下行作为我的表中的示例
id shop_id start_time end_time
1 21 10:00 11:00
我想检查表中是否存在start_time和end_time我是否正在使用以下查询但不能正常工作,我哪里错了?
select *
from usr_booking
where shop_id='21'
and start_time between '10:10:00' and '11:01:00'
or end_time between '10:10:00' and '11:01:00'
您需要明确区分shop_id
上的检查和时间范围:
SELECT *
FROM usr_booking
WHERE
shop_id = 21 AND
(start_time BETWEEN '10:10:00' AND '11:01:00' OR
end_time BETWEEN '10:10:00' AND '11:01:00');
MySQL中的AND
运算符优先于OR
运算符。所以,您当前的查询实际上正在评估如下:
SELECT *
FROM usr_booking
WHERE
(shop_id = 21 AND
start_time BETWEEN '10:10:00' AND '11:01:00') OR
end_time BETWEEN '10:10:00' AND '11:01:00';
显然,这与您可能想要的逻辑不同。
尝试在此类查询中创建组
select * from usr_booking where shop_id='21' AND ((start_time between '10:10:00' and '11:01:00') OR (end_time between '10:10:00' and '11:01:00'))
添加额外的括号制作组。
试试这个查询:
SELECT *
FROM usr_booking
Where shop_id='21' AND start_time BETWEEN '10:10:00' AND '11:01:00'
AND end_time BETWEEN '10:10:00' AND '11:01:00'
试试这个
SELECT * FROM usr_booking WHERE shop_id=21 AND (start_time BETWEEN '10:10:00' AND '11:01:00') OR (end_time BETWEEN '10:10:00' AND '11:01:00')
如果给你时间'10:10:00'和'11:01:00'并且你想知道是否有任何重叠的那个时期,那么逻辑是:
select b.*
from usr_booking
where shop_id = 21 and -- do not use single quotes for numeric constants (assuming `shop_id` is a number
end_time > '10:10:00' and
start_time < '11:01:00';
对于重叠间隔,between
不合适。