为每个不同的行选择计数(mysql和php)

时间:2020-12-10 09:14:45

I am using mysql and php.

我正在使用mysql和php。

I have a table with one column. I can show unique rows by:

我有一个有一列的表。我可以显示以下行:

select distinct id from id_table

This might show

这可能表明

1
2
3
5

What I want to do is show the number of 1's, 2's, etc there are.

我想要做的是显示1,2的数量等。

I could do

我可以

select count(id) from id_table where id = 1

But then I have to run a query for every... single... row... And with hundreds of thousands of rows, not good.

但后来我必须为每一个......单行...运行一个查询...并且有数十万行,不好。

Is there a way to return an array of the counts of each distinct item

有没有办法返回每个不同项的计数数组

Data

数据

1, 1, 1, 2, 3, 3, 5

Results

结果

3, 1, 2, 1

Thanks

谢谢

1 个解决方案

#1


20  

select id, count(id)
from table
group by id

If only want count of ids, then

如果只想要ID数,那么

select count(id)
from table
group by id

Here is a simple tutorial of group by clause

这是group by子句的简单教程

http://www.w3schools.com/sql/sql_groupby.asp

http://www.w3schools.com/sql/sql_groupby.asp

#1


20  

select id, count(id)
from table
group by id

If only want count of ids, then

如果只想要ID数,那么

select count(id)
from table
group by id

Here is a simple tutorial of group by clause

这是group by子句的简单教程

http://www.w3schools.com/sql/sql_groupby.asp

http://www.w3schools.com/sql/sql_groupby.asp