我有下表
ID Color
1 red
2 red
3 red
4 blue
5 blue
6 yellow
我需要的结果:
答案 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']."      ".$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
如果您有red
和light red
,则会有自己的计数。