The following query should do the trick, it is almost the same as your code, but the last bit is different:
select
image_id,
count(*)
from
favourites
group by
image_id
order by
count(*) desc
limit 10
You might also want to have a read of Q&A that I wrote which covers off a lot of stuff like this in a great deal of depth.
Edit:
To answer one of the comments below, does using count(*)
in the order by
statement cause it to calculate again?
No.
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)
You can see from this that it stores the data in temporary
and uses it from there.