Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

datetime - MySQL: Is it possible to create a query that evaluates data from different records?

I've got a table like this. It shows the starttime and endtime of different restaurants on different weekdays.

No Restaurant Weekday Starttime Endtime
1 A Mon 10:00 21:00
2 A Tue 10:00 21:00
3 A Wed 19:00 08:00
4 A Thu
5 A Fri 10:00 21:00
6 A Sat 10:00 21:00
7 A Sun 19:00 08:00
8 B Mon 11:00 21:00
9 B Tue 11:00 21:00
10 B Wed 11:00 23:00
11 B Thu 11:00 23:00
12 B Fri 11:00 16:00
13 B Sat 10:00 00:00
14 B Sun 00:00 13:00
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can split to 2 rows each row that contains Endtime of the next day:

WITH cte AS (
  SELECT *, Weekday day, Starttime time1, Endtime time2 FROM user_time
  WHERE Starttime < Endtime 
  UNION ALL
  SELECT *, Weekday, Starttime, '23:59' FROM user_time
  WHERE Starttime > Endtime 
  UNION ALL
  SELECT *, 
         DATE_FORMAT((STR_TO_DATE(CONCAT(LEFT(CURRENT_DATE, 8), Weekday), '%X-%V-%W') + INTERVAL 1 DAY), '%a'), 
         '00:00', Endtime 
  FROM user_time
  WHERE Starttime > Endtime
)  
SELECT No, Restaurant, Weekday, Starttime, Endtime 
FROM cte
WHERE day = DATE_FORMAT(CURRENT_DATE, '%a')
  AND NOW() BETWEEN CONCAT(CURRENT_DATE, ' ', time1, ':00') AND CONCAT(CURRENT_DATE, ' ', time2, ':00') 

See the demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...