简体   繁体   中英

MYSQL count for each value in field

I have a database with the following table "responses" with an id and a US state:

*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

So, my output would look like:
CA: 1
NY: 2
CO: 1
DE: 1
etc...

I know I can run 50 queries like so:

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?

Use a GROUP BY clause:

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.

You can use MySQL's GROUP BY clause which will group all of the results by the state :

SELECT
    state, COUNT(*) AS count
FROM
    `responses`
GROUP BY
    state;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM