mysql查询选择计数列不同?

时间:2014-12-29 05:01:37

标签: 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百万行,我需要更快的查询。谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

你可以这样做:

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

这里是fiddle

答案 1 :(得分:0)

为该特定字段应用索引并继续使用此查询....我希望它能为您提供更好的性能

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

答案 2 :(得分:-1)

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

如果查询似乎很慢,请尝试在表格上添加索引