在没有“filesort”和“using temporary”的情况下,有没有办法在MySQL中使用group by?尝试了不同的索引,不同的broup,不同的顺序但总是相同的结果 - “使用filesort”或“使用filesort +使用临时”。
CREATE TABLE IF NOT EXISTS `ank1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL DEFAULT '0',
`kmk` int(3) NOT NULL,
`order_by` int(11) NOT NULL,
`gender` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `gender` (`gender`,`kmk`,`uid`,`order_by`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
mysql> explain SELECT gender, kmk, order_by FROM ank1
-> where
-> gender IN (1, 2, 3) and
-> kmk IN (1, 2, 3, 12, 13, 23, 123)
-> group by uid
-> order by order_by DESC limit 0, 30;
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
| 1 | SIMPLE | ank1 | index | gender | gender | 13 | NULL | 6 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
1 row in set (0.00 sec)
即使按同一列分组和排序也会给出相同的结果:
CREATE TABLE IF NOT EXISTS `ank1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL DEFAULT '0',
`kmk` int(3) NOT NULL,
`order_by` int(11) NOT NULL,
`gender` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `gender` (`gender`,`kmk`,`order_by`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
mysql> explain SELECT gender, kmk, order_by FROM ank1
-> where
-> gender IN (1, 2, 3) and
-> kmk IN (1, 2, 3, 12, 13, 23, 123)
-> group by order_by
-> order by order_by DESC limit 0, 30;
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
| 1 | SIMPLE | ank1 | index | gender | gender | 9 | NULL | 6 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------------------------------------------------+
1 row in set (0.00 sec)