MySQL MAX () with GROUP BY
source link: https://www.codesd.com/item/mysql-max-with-group-by.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
MySQL MAX () with GROUP BY
Considering these entries:
INSERT INTO `schedule_hours` (`id`, `weekday`, `start_hour`) VALUES
(1, 1, '09:00:00'),
(2, 2, '09:00:00'),
(3, 3, '09:00:00'),
(4, 4, '09:00:00'),
(5, 5, '09:00:00'),
(6, 6, NULL),
(7, 7, NULL),
(8, 1, '12:00:00');
I'm running the following query:
SELECT MAX(id), weekday, start_hour
FROM schedule_hours
GROUP BY weekday
ORDER BY weekday
The objective is to get a whole week (weekday 1-monday, 2-tuesday, etc...) but return the most recent entries.
So, in my table I now have 2 entries for Monday and 1 entry for the rest of the days, I only want to return the latest ones (id is an increment field), the right result should be:
8 1 12:00:00
2 2 09:00:00
3 3 09:00:00
4 4 09:00:00
5 5 09:00:00
6 6 NULL
7 7 NULL
What I'm currently getting:
8 1 09:00:00 < wrong
2 2 09:00:00
3 3 09:00:00
4 4 09:00:00
5 5 09:00:00
6 6 NULL
7 7 NULL
The id and weekday columns are correct, but the first row is showing a wrong result for the start_hour column!
You should try this query:
SELECT id, weekday, start_hour
FROM schedule_hours
WHERE id IN (
SELECT MAX(id)
FROM schedule_hours
GROUP BY weekday
)
ORDER BY weekday
Currently in your query, the columns in SELECT
clause are different from the columns in GROUP BY
clause. In standard SQL, your query is illegal and will result in a syntax error. However, MySQL extends the use of GROUP BY
so that the select list can refer to nonaggregated columns not named in the GROUP BY clause, which is why you are not getting an error but the output is not what you are expecting. For more details, you may read MySQL Extensions to GROUP BY.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK