简体   繁体   English

在SQL中获取可用时间和预订时间

[英]Get available and booked time in sql

I have two tables in mysql (shop_details,booking) 我在mysql中有两个表(shop_details,booking)

shop_details 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(1),那么我想每半小时获取预订时间(开店时间之后)和可利用的时间(到开店为止),例如,我想要跟踪结果

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: 您需要一个时间列表-然后可以使用join或相关子查询获取信息:

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 首先,使用while函数创建一个循环,该循环将重复执行该代码,直到达到关闭时间为止,而在while函数内部,您可以使用IF语句根据日期确定可用性状态

goold luck 高德运气

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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