我有这个查询需要 27 秒才能执行:
SELECT ocal_files.*, count(DISTINCT ocal_favs.username) as favs
FROM ocal_files
INNER JOIN ocal_favs on ocal_favs.clipart_id = ocal_files.id
GROUP BY ocal_files.id
ORDER BY favs DESC
(而不是用户名,它应该是 user_id,因为我有用户表)
ocal_files
有 37457 行,ocal_favs
有 18263
编辑解释的结果
mysql> EXPLAIN SELECT ocal_files.*, count(DISTINCT ocal_favs.username) as favs FROM ocal_files INNER JOIN ocal_favs on ocal_favs.clipart_i
d = ocal_files.id GROUP BY ocal_files.id ORDER BY favs DESC;
+----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+
| 1 | SIMPLE | ocal_favs | ALL | rlb_clipart_id | NULL | NULL | NULL | 18622 | Using temporary; Using filesort|
| 1 | SIMPLE | ocal_files | eq_ref | PRIMARY | PRIMARY | 4 | openclipart.ocal_favs.clipart_id | 1 | Using where |
+----+-------------+------------+--------+----------------+---------+---------+---------------------------------+-------+---------------------------------+
2 rows in set (0.00 sec)
为什么慢?可以优化吗?如果是,那怎么办?