[英]MYSQL count for each value in field
I have a database with the following table "responses" with an id and a US state: 我有一个数据库,其中包含下表“响应”,其中包含id和美国州:
*id *state
1 CA
2 NY
3 NY
4 CO
5 DE
I'm using PHP to output the total number of rows for each of the 50 states in the US 我正在使用PHP输出美国50个州中每个州的总行数
So, my output would look like: 所以,我的输出看起来像:
CA: 1 CA:1
NY: 2 纽约:2
CO: 1 CO:1
DE: 1 DE:1
etc... 等等...
I know I can run 50 queries like so: 我知道我可以运行50个查询:
SELECT *
FROM `responses`
WHERE state='CA'
My question is: is there a more efficient way to handle this, or do I need to run 50 queries? 我的问题是:有更有效的方法来处理这个问题,还是我需要运行50个查询?
Use a GROUP BY
clause: 使用
GROUP BY
子句:
SELECT state, COUNT(*) FROM `responses` GROUP BY state;
There are many good tutorials on using GROUP BY, and it's one of the most useful and powerful features of SQL. 有很多关于使用GROUP BY的好教程 ,它是SQL最有用和最强大的功能之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.