SQL将行计数在一起

时间:2011-12-03 20:25:35

标签: php mysql

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的行数?表名为orders

以上示例我希望它输出:

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

我只知道如何使用一些php循环来做这个更复杂的事情

3 个答案:

答案 0 :(得分:2)

此处使用的模式是COUNT()GROUP BY结合使用:

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

您将获得两列可以根据需要轻松重新格式化的列。

答案 1 :(得分: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>

答案 2 :(得分:0)

SELECT item_id, COUNT(id) FROM orders 
GROUP BY item_id
相关问题