I have a table in MySQL that holds rows of days from 1 to 7 (Monday to Sunday), i want to get a full week of rows to 1 to 7 based on a specific date the date is null in some rows and set in some rows:
id | day | date |
---|---|---|
1 | 1 | NULL |
2 | 2 | NULL |
3 | 3 | NULL |
4 | 4 | NULL |
5 | 5 | NULL |
6 | 6 | NULL |
7 | 7 | NULL |
8 | 3 | 2024-05-29 |
i would like to select the week and it should include the specific date so for example selecting the week based on 2024-05-29 should give me this result:
id | day | date |
---|---|---|
1 | 1 | NULL |
2 | 2 | NULL |
8 | 3 | 2024-05-29 |
4 | 4 | NULL |
5 | 5 | NULL |
6 | 6 | NULL |
7 | 7 | NULL |
and if a select a date that doesn’t exist like 2024-05-05 it should give me:
id | day | date |
---|---|---|
1 | 1 | NULL |
2 | 2 | NULL |
3 | 3 | NULL |
4 | 4 | NULL |
5 | 5 | NULL |
6 | 6 | NULL |
7 | 7 | NULL |
is this possible to do with a single query? otherwise how would you go about doing something like this? thank you
edit: im on Mysql version 8.0
2
Answers
Here is the query that i came up with which does work exactly how i wanted it, if anyone has any remarks on how to optimize this or any other solution i would love to hear it:
Group by
day
, use a conditional to returnNULL
when thedate
column doesn’t match the given date, otherwise thedate
column. Then useMAX()
to prefer that row.