2015-10-03 51 views
0

我有如下表每個項目數行

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

結果我需要:

  • 紅3
  • 藍2
  • 黃1
+0

這是一個數據庫表? – chris85

+0

這是一個html表,數據庫表還是什麼? – marmeladze

+0

這是什麼?數據庫表? PHP的? HTML?或whaat? – user5173426

回答

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

這應該假設顏色名稱是con,給你一個數據庫中每種顏色的數量sistent。

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

如果你有redlight red這些都會有自己的計數。

+0

結果如何?回聲「????」 –

+0

是的,你可以迴應結果。你在問題中顯示的所有內容都是數據庫結構,所以我推測你想要的只是查詢你的數據庫來獲得結果。 – chris85

+0

感謝您的重播,如何統計每個項目的行數?我需要的結果如上 –