以下查询应该可以解决问题,它与您的代码几乎相同,但最后一点不同:
select
image_id,
count(*)
from
favourites
group by
image_id
order by
count(*) desc
limit 10
你可能还想读一读我写的问答,它深入地涵盖了很多这样的东西。
编辑:
要回答以下评论之一,语句中count(*)
的using 是否order by
会导致它再次计算?
不。
mysql> select * from test2;
+------+-------+-------+
| id | barry | third |
+------+-------+-------+
| 1 | ccc | NULL |
| NULL | d | 1 |
| NULL | d | 2 |
| NULL | d | 3 |
+------+-------+-------+
4 rows in set (0.00 sec)
mysql> explain select barry, max(third) from test2;
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| 1 | SIMPLE | test2 | ALL | NULL | NULL | NULL | NULL | 4 | |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
1 row in set (0.11 sec)
mysql> explain select barry, max(third) from test2 order by barry;
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| 1 | SIMPLE | test2 | ALL | NULL | NULL | NULL | NULL | 4 | |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
1 row in set (0.00 sec)
mysql> explain select barry, max(third) from test2 order by max(third);
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
| 1 | SIMPLE | test2 | ALL | NULL | NULL | NULL | NULL | 4 | Using temporary |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
1 row in set (0.00 sec)
您可以从中看到它存储数据temporary
并从那里使用它。