[英]SQL Counting rows together
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循环来做些复杂的事情
这里使用的模式是COUNT()
与GROUP BY
结合使用:
SELECT item_id, COUNT(id) AS item_count FROM orders GROUP BY item_id
您将获得两列,可以根据需要轻松地重新设置其格式。
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>
SELECT item_id, COUNT(id) FROM orders
GROUP BY item_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.