2011-12-03 103 views
0
id partner_id date_created status item_id 
3 2 1322861013 redirected 1 
4 2 1322943245 redirected 6 
5 3 1322943246 redirected 6 
6 2 1322943247 redirected 6 

如何計算具有相同item_id的行數?表名是上述我希望它輸出ordersSQL一起計算行

例子:

There's 3 rows with the item_id 6 
There's 1 rows with the item_id 1 

我只知道如何做到這一點稍微複雜一些的PHP循環

回答

0
SELECT item_id, COUNT(id) FROM orders 
GROUP BY item_id 
1
mysql> create table test(
    ->  row integer 
    ->) ; 
Query OK, 0 rows affected (0.05 sec) 

mysql> insert into test values (3) , (3) , (3) , (1) ; 
Query OK, 4 rows affected (0.00 sec) 
Records: 4 Duplicates: 0 Warnings: 0 

mysql> select count(*) from test group by row; 
+----------+ 
| count(*) | 
+----------+ 
|  1 | 
|  3 | 
+----------+ 
2 rows in set (0.03 sec) 

mysql> 
+0

+1這是一個很好的例子 –

2

這裏使用的模式是COUNT()加上GROUP BY

SELECT item_id, COUNT(id) AS item_count FROM orders GROUP BY item_id 

您將返回兩列,可根據需要輕鬆重新格式化。