I have a table with opening_hoursfor restaurants:
SELECT * FROM opening_hours;
+----+---------------+------------+----------+-----+
| id | restaurant_id | start_time | end_time | day |
+----+---------------+------------+----------+-----+
| 1 | 1 | 12:00:00 | 18:00:00 | 1 |
| 2 | 1 | 09:00:00 | 19:00:00 | 4 |
| 3 | 2 | 09:00:00 | 16:00:00 | 4 |
| 4 | 2 | 09:00:00 | 16:00:00 | 5 |
| 5 | 3 | 09:00:00 | 16:00:00 | 4 |
| 6 | 3 | 09:00:00 | 16:00:00 | 5 |
| 7 | 3 | 09:00:00 | 16:00:00 | 1 |
| 8 | 3 | 09:00:00 | 16:00:00 | 6 |
+----+---------------+------------+----------+-----+
http://www.sqlfiddle.com/#!2/eaea09/1
Now I want to get the βclosestβ the next day or the same day for each restaurant on the current day. For example, if the current day 1, the result would be:
restaurant_id: 1 day: 1
restaurant_id: 2 day: 4
restaurant_id: 3 day: 1
In the case of the day, 1I could do this:
SELECT day FROM opening_hours WHERE day >= 1 GROUP BY restaurant_id LIMIT 1
But if today is 6, it will not work. I will need a query to get the maximum number of days ( 7), and if this could not be found, it should start again with 1. Thus, the result for the day 6will be in this case:
restaurant_id: 1 day: 1
restaurant_id: 2 day: 4
restaurant_id: 3 day: 6
How can I achieve this with a query?
I think it could be something like this in pseudo SQL:
SELECT `day` FROM opening_hours WHERE `day` >= 'today' IF NOT FOUND WHERE `day` >= 1 GROUP BY `restaurant_id` LIMIT 1
edit:
2 , . , . .