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

Glo*_*ooh 3 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  |
+------+--------+-----------+-------+
Run Code Online (Sandbox Code Playgroud)

我希望有一个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;
Run Code Online (Sandbox Code Playgroud)

如何将其合并为一个SQL?我应该使用CONCAT或TOP还是其他东西?我使用MySQL和PHP.

liq*_*car 7

你需要GROUP BY和SUM

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC
Run Code Online (Sandbox Code Playgroud)

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

SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC LIMIT 10`
Run Code Online (Sandbox Code Playgroud)

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

  +-----------+-------------+
  | owner_id  |  owner_name |
  +-----------+-------------+
  |     1     |    John     |
  |     2     |    Pete     |
  |     3     |    Mary     |
  +-----------+-------------+
Run Code Online (Sandbox Code Playgroud)

然后owner_id在你的books表中引用它.