0

Hello everyone i have the following row as a sample in my table

id      shop_id     start_time      end_time
1       21          10:00           11:00

and i want to check whether start_time and end_time exist in table or not I am using following query but not working correctly, Where i am wrong ?

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'
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55

5 Answers5

2

You need to clearly separate the checks on the shop_id and the time ranges:

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');

The AND operator in MySQL has higher precedence than the OR operator. So, your current query is actually evaluating as this:

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';

Clearly, this is not the same logic as you what you probably intended.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • this wont work if start time is 14:00 and end time is 09:00 (i.e next day) any solution for this? – paradox May 28 '20 at 21:05
0

Try to make groups in such type of queries

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'))

Add the extra brackets make groups.

Sanjit Bhardwaj
  • 893
  • 7
  • 13
0

Try this Query:

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'
Nimesh Patel
  • 796
  • 1
  • 7
  • 23
0

Try this

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')
Ram
  • 84
  • 7
0

If you are given the times '10:10:00' and '11:01:00' and you want to know if anything overlaps with that period, then the logic is:

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';

For overlapping intervals, between is not appropriate.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786