Skip to content
Advertisement

How to make an SQL query to get only 1 row with specific data?

I have the following MySQL query:

The logic of the query is to get opening hours for the restaurant. There’re 2 types of open hours:

  • Permanent. It is default opening hours for restaurant for every day
  • Specific. It is a row that contains the range between from_date and until_date dates when this schedule works.

Query gets the rows which:

  • has current day of week in ISO format ISO (1 => Monday etc)
  • where current date is in the range of from_date and until_date (custom restaurant schedule) or from_date and until_date equals to NULL (default restaurant schedule)
  • where is_closed column equals to 0 (if the column equals to 0, then the restaurant closed today)

And then I sort the result by from_date and until_date and limit the result by 1 row, so if restaurant has a custom schedule, then I’ll take the row that contains custom schedule for today. If no, I’ll take the row with default schedule.

The problem: this query allows to get opening hours for certain restaurant (I have to execute this query for each restaurant). It makes the N+1 problem if I want to get the list of the open restaurants.

Question: what is the query that will find open restaurants?

restaurant_working_times table schema

I want to get the output with the following columns:

There should be only open restaurants, so open restaurant means that we found the row with restaurant_id where current time greater than from_hour and less than until_hour. Also I should repeat that “custom” schedule has a higher priority than “default” schedule. “custom” schedule means that from_date and until_date are not equal to null. If there’s no custom schedule for the day — we take “default” schedule, if there’s no default schedule — the restaurant is closed today.

Advertisement

Answer

This is a prioritization problem. For each restaurant, you want the row with dates to have the priority. To accomplish this, you can use window functions:

EDIT:

In older versions of MySQL, you can phrase this as:

Note that the number of parameters has changed. This is a case where named parameters would be helpful.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement