2014-10-30 25 views
0

有一點我堅持。我有一個表在我的數據庫,如:PHP MySQLi如何從表格中獲得最重複的值

id | AuthorId | Book 
--------------------- 
1 | 2  | book name 
2 | 2  | book name 
3 | 2  | book name 
4 | 2  | book name 
5 | 5  | book name 
6 | 5  | book name 
7 | 8  | book name 
8 | 9  | book name 
9 | 9  | book name 
10 | 6  | book name 

正如你可以看到,作者ID爲「2」被重複最高的次在該表(4次),而作者作者的ID出現少於4次。如何使用php MySQLi從這個表中獲取ID「2」,這是該數據中最常出現的值?我不知道我該怎麼做。

非常感謝。

+3

使用'WHERE'子句。 I.e .:'WHERE AuthorId = 2'和'GROUP BY',和/或MySQL的'COUNT()'聚合函數。 – 2014-10-30 20:14:52

回答

2

請嘗試以下查詢。您可以對按照AuthorID DESC分組的行進行計數,並將結果限制爲最高值。

SELECT AuthorId, COUNT(AuthorId) as c from table 
GROUP BY AuthorId 
ORDER BY COUNT(AuthorId) DESC 
LIMIT 1; 
+0

make suer'AuthorId'被編入索引 – 2014-10-30 20:23:02

+0

謝謝,作品像一個魅力。 – 2014-10-30 20:46:57

1

試試這個

select AuthorId , count(AuthorId) as max 
from table_name 
group by AuthorId order by max desc limit 1; 

order by max desc是在第一行訂購最大值。 limit 1從獲取僅第一行

相關問題