计算每个项目的行数

时间:2015-10-03 19:11:39

标签: php count

我有下表

ID     Color
 1       red
 2       red
 3       red 
 4       blue
 5       blue
 6       yellow

我需要的结果:

  • red 3
  • blue 2
  • 黄色1

2 个答案:

答案 0 :(得分:2)

我也有某种数据库。

mysql> select * from taggings LIMIT 10;
+--------+---------+
| tag_id | post_id |
+--------+---------+
|      2 |      14 |
|      3 |       2 |
|      4 |       1 |
|      4 |       2 |
|      4 |       3 |
|      4 |       4 |
|      4 |       5 |
|      4 |      14 |
|      4 |      19 |
|      6 |       1 |
+--------+---------+
10 rows in set (0.00 sec)

mysql> select post_id, count(tag_id) from taggings GROUP BY(post_id);
+---------+---------------+
| post_id | count(tag_id) |
+---------+---------------+
|       1 |             9 |
|       2 |             3 |
|       3 |             2 |
|       4 |             1 |
|       5 |             3 |
|       6 |             3 |
|       9 |             1 |
|      10 |             3 |
|      11 |             4 |
|      14 |            10 |
|      15 |             4 |
|      16 |             2 |
|      17 |             4 |
|      18 |             5 |
|      19 |             7 |
|      20 |             2 |
+---------+---------------+
16 rows in set (0.00 sec)
从现在开始,php代码很简单。

<?php 
$cn = mysqli_connect(/*connection details*/);
$sql = "select post_id, count(tag_id) from taggings GROUP BY(post_id);";
$d = mysqli_query($cn, $sql);
echo "post id \t tag count";
echo "<ul>";    
while ($row = mysqli_fetch_assoc($d)) {
echo "<li>";    
echo $row['post_id']."&nbsp &nbsp &nbsp ".$row['count(tag_id)']."<br>"; 
//you will use $row['color'] and $row['count(id)'] 
echo "</li>";   
}
echo "</ul>"?>

输出html

post id tag count

1      9
2      3
3      2
4      1
5      3
6      3
9      1
10      3
11      4
14      10
15      4
16      2
17      4
18      5
19      7
20      2

答案 1 :(得分:1)

假设颜色名称一致,这应该为您计算数据库中的每种颜色。

select color, count(*) from table group by color

如果您有redlight red,则会有自己的计数。