2014-12-29 174 views
-1

我使用MySQL和我有...Mysql查詢選擇計數列不同?

orders 
+--------+---------+-------------+ 
| ID  | PRO_ID | CUS_ID  | 
+--------+---------+-------------+ 
| 1  | 1  | 2   | 
| 2  | 1  | 79   | 
| 3  | 1  | 6   | 
| 4  | 2  | 41   | 
| 5  | 2  | 28   | 
| 6  | 2  | 33   | 
| 7  | 3  | 2   | 
| 8  | 4  | 9   | 
| 9  | 4  | 23   | 
| 10  | 5  | 43   | 
| 11  | 5  | 45   | 
| 12  | 5  | 78   | 
| 13  | 5  | 67   | 
| 14  | 6  | 12   | 
| 15  | 6  | 95   | 

如何獲得5個頂級PRO_ID及其數量。例如

+---------+-------------+ 
| PRO_ID | COUNT  | 
+---------+-------------+ 
| 5  | 4   | 
| 1  | 3   | 
| 2  | 3   | 
| 4  | 2   | 
| 6  | 2   | 

訂單表有2個百萬行,我需要一個查詢更快。謝謝你的幫助!

回答

1

申請索引該特定領域,繼續這個查詢....我希望它會給你更好的表現

select PRO_ID,count(PRO_ID) as prod_count 
from orders 
group by PRO_ID 
order by prod_count desc 
limit 5 
0
select PRO_ID,count(PRO_ID) as count 
from orders 
group by PRO_ID 
order by count desc 
limit 5 

如果查詢似乎慢然後嘗試在你的餐桌添加索引

+0

我認爲OP需要按照count的順序。我認爲這就是他正在試圖解釋的期望輸出 –

0

你可以這樣做:

select PRO_ID, COUNT(*) as total 
from test 
group by PRO_ID 
ORDER BY total desc, PRO_ID 
limit 5 

這裏是fiddle