大家好,我在表中有以下一行作为示例
id shop_id start_time end_time
1 21 10:00 11: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'
答案 0 :(得分:2)
您需要明确区分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';
很显然,这与您可能想要的逻辑不同。
答案 1 :(得分:0)
尝试按此类查询进行分组
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'))
添加多余的括号进行分组。
答案 2 :(得分:0)
尝试此查询:
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'
答案 3 :(得分:0)
尝试一下
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')
答案 4 :(得分:0)
如果给定时间'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
是不合适的。