2012-04-06 43 views
3

我有一個我似乎無法處理的挑戰。如何在MySQL中使用組合數據行獲得TOP 10?

+------+--------+-----------+-------+ 
| 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。

回答

7

您需要GROUP BY與SUM

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_idbooks表中引用此。

+0

如果我使用GROUP BY,我是否不跳行?他們都會被包含在SUM()中嗎? 關於您關於正常化點...你是正確的,但我用一個例子在這裏得到簡單:-) – Glooh 2012-04-06 12:28:21

+1

@glooh這就是GROUP BY的地步。它會爲每個用戶的所有行進行求和。 – liquorvicar 2012-04-06 12:48:32

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

你寫ORDER BY SUM(books),但是liquorvicar寫ORDER BY total_books,因爲他早先說過total_books,就像'total'一樣。有什麼更好的使用? – Glooh 2012-04-06 12:27:05

+1

我建議使用liquorvicar的方法。 – 2012-04-06 12:31:11

1
SELECT sum(books) as book_count, user FROM `books` GROUP BY (user) order by book_count DESC 
相關問題