I have a table which contains nearly 1 million+ records. I want to find the max record of each group. Here is my sql:
SELECT *
FROM t
WHERE id IN (SELECT max(id) AS id
FROM t
WHERE a = 'some' AND b = 0
GROUP BY c, d);
Table declares as follow.
CREATE TABLE `t` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`a` varchar(32) NOT NULL COMMENT 'a',
`b` tinyint(3) unsigned NOT NULL COMMENT 'b',
`c` bigint(20) unsigned NOT NULL COMMENT 'c',
`d` varchar(32) NOT NULL COMMENT 'd',
PRIMARY KEY (`id`),
KEY `idx_c_d` (`c`,`d`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='test table';
I have a union index on c and d. So the second statement(SELECT max(id) AS id FROM t WHERE a = 'some' AND b = 0 GROUP BY c, d) execute in 200ms. But the total statement cost nearly 6 seconds(The result contains 5000 rows).
Here is the explain shows(some columns are omitted).
+-------------+-------+-------+---------------+--------+---------+----------+--------------------------+
| select_type | table | type | possible_keys | key | rows | filtered | Extra |
+-------------+-------+-------+---------------+--------+---------+----------+--------------------------+
| PRIMARY | t | ALL | NULL | NULL | 9926024 | 100.00 | Using where |
| SUBQUERY | t | index | idx_1 | idex_1 | 9926024 | 1.00 | Using where; Using index |
+-------------+-------+-------+---------------+--------+---------+----------+--------------------------+