1

我有一个简单的 Web 应用程序,当用户单击图像上的收藏夹时,数据库存储用户 ID 和他们正在查看的图像 ID,表格如下所示:

Favorites
---------------------
-user_id - image_id -
---------------------
-abc     - 123      -
-abc     - 456      -
-def     - 123      -
---------------------

我试图找到前 10 个最喜欢的图像(全球),即总体上最受欢迎的 10 个图像。该查询只需要找到最常出现的 10 个 image_id 值。到目前为止,我已经尝试了一些类似的东西

SELECT image_id, COUNT(*) FROM favourites GROUP BY image_id LIMIT 100 ORDER DESC

完成此任务的正确查询是什么?

4

2 回答 2

6

以下查询应该可以解决问题,它与您的代码几乎相同,但最后一点不同:

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并从那里使用它。

于 2013-09-03T10:43:28.663 回答
0

尝试这个:

SELECT
  image_id, count(image_id)
FROM Favorites
GROUP BY image_id
ORDER BY 2 DESC
LIMIT 10
于 2013-09-03T10:47:16.343 回答