如何在MySQL中使用组合数据行获得TOP 10?

时间:2012-04-06 12:01:05

标签: php mysql select

我遇到了一个我无法处理的挑战。

+------+--------+-----------+-------+
|  id  |  user  |  genres   | books |
+------+--------+-----------+-------+
|  1   |  John  |  crimes   |   2   |
|  2   |  John  |  scienc   |   1   |
|  3   |  John  |  nature   |   4   |
|  4   |  Pete  |  nature   |   3   |
|  5   |  Pete  |  crime    |   2   |
|  6   |  Mary  | nature    |   20  |
+------+--------+-----------+-------+

我希望有一个SQL查询来获取用户拥有的书籍总数,无论该类型是什么,并且想要由最多的人订购。

在这个例子中,你看到玛丽有20本书,皮特5和约翰有7本,所以我想要的结果就是这样的数组:

result[0][user] = "Mary";
result[0][total] = 20;
result[1][user] = "John";
result[1][total] = 7;
result[2][user] = "Pete";
result[2][total] = 5;

如何将其整合到一个SQL中?我应该使用CONCAT或TOP还是其他东西?我使用MySQL& PHP。

3 个答案:

答案 0 :(得分:7)

您需要带有SUM的GROUP BY

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC

如果您只想要前10个,那么您可以使用

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC LIMIT 10`

顺便说一下,您可能需要稍微重新考虑您的架构。复制信息违反了规范化原则。您可能想要添加新的owners表:

  +-----------+-------------+
  | owner_id  |  owner_name |
  +-----------+-------------+
  |     1     |    John     |
  |     2     |    Pete     |
  |     3     |    Mary     |
  +-----------+-------------+

然后在owner_id表格中books引用此内容。

答案 1 :(得分:2)

select user, sum(books) as total
from your_table
group by user
order by sum(books)
limit 10

答案 2 :(得分:1)

SELECT sum(books) as book_count, user  FROM `books` GROUP BY (user) order by book_count DESC