Show create table structure with;
CREATE TABLE `quote` (
`id` int(8) unsigned NOT NULL AUTO_INCREMENT,
`code` text COLLATE utf8mb4_unicode_ci,
`date` date DEFAULT NULL,
`open` double DEFAULT NULL,
`high` double DEFAULT NULL,
`low` double DEFAULT NULL,
`close` double DEFAULT NULL,
`volume` bigint(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17449887 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
Find the records for each code having the maximum date with inner join such as:
SELECT q1.*
FROM quote q1
INNER JOIN
(
SELECT code, MAX(date) AS max_date
FROM quote
GROUP BY code
) q2
ON q2.code = q1.code AND
q2.max_date = q1.date;
I wonder why the subquery can't get desired result as above:
select * from quote group by code having date=max(date);
Please explain the reason in detail.
To start with:
This query itself is not a valid one from SQL Standard perspective.
It could be, if all other columns were functionally dependent on
code, which is not the case based on table definition(code is not unique and not a primary key). Related reading: Group by clause in mySQL and postgreSQL, why the error in postgreSQL?The query behaves kind of ANY_VALUE:
Regarding second part:
Here the condition in
HAVINGapplies after aggregation, which means the comparison is between MAX(date) per code compared to "unspecified" date.Illustrating with example(this code will work only if
only_full_group_byis turned off):And queries:
db<>fiddle demo
Saying so, in order to get all columns ranking functions MySQL 8.0+ could be used:
db<>fiddle demo 2