简体   繁体   中英

Get available and booked time in sql

I have two tables in mysql (shop_details,booking)

shop_details

id      shop_id     open_time       close_time
1       1           09:00Am         09:00Pm
2       5           10:00Am         09:00Pm

booking

id      shop_id     start_time      end_time
1       1           10:30am         11:10Am
1       5           02:00pm         02:45pm

Now I want if I want to know about shop_id (1) then I want to get booked time (after shop open time) and avaliable time (till shop close) with every half hour, for example I want following result

shop_id     start_time      end_time    status
1           09:00am         09:30am     avaliable
1           09:30am         10:00am     avaliable
1           10:00am         10:30am     avaliable
1           10:30am         11:10am     booked
1           11:10am         11:40am     avaliable
...
1           08:30am         09:00pm     booked

You need a list of times -- then you can get the information using a join or correlated subquery:

select t.tme,
       (case when exists (select 1
                          from booking b
                          where b.start_time <= t.tme and
                                b.end_time > t.tme
                         )
             then 'booked' else 'available'
        end) as status
from (select cast('00:00' as time) as tme union all
      select cast('00:30' as time) as t union all
      select cast('01:00' as time) as t union all
      . . .
      select cast('23:50' as time) as t
     ) t join
     (select sd.*
      from shop_details sd
      where sd.shop_id = 1
     ) sd1
     on t.tme >= sd1.open_time and
        t.tme <= sd1.close_time;

first, use while function to create a loop that will repeat the code until reaching close time, inside while function, u can use IF statement to make Availability status base on dates

goold luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM