如何在同一行中使用 MySQL 显示不同记录的计数?
为此,你可以将 GROUP_CONCAT()、COUNT() 与 GROUP BY 子句一起使用。让我们先创建一个表格 −
mysql> create table DemoTable -> ( -> CompanyId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> CompanyName varchar(20) -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 命令在表格中插入一些记录 −
mysql> insert into DemoTable(CompanyName) values('Amazon'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(CompanyName) values('Google'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(CompanyName) values('Google'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(CompanyName) values('Microsoft'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(CompanyName) values('Amazon'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(CompanyName) values('Amazon'); Query OK, 1 row affected (0.07 sec)
使用 select 语句从表格中显示所有记录 −
mysql> select *from DemoTable;
这将生成以下输出 −
+-----------+-------------+ | CompanyId | CompanyName | +-----------+-------------+ | 1 |Amazon | | 2 |Google | | 3 |Google | | 4 |Microsoft | | 5 |Amazon | | 6 |Amazon | +-----------+-------------+ 6 rows in set (0.00 sec)
以下是如何使用 MySQL 显示同一行中不同记录的计数 −
mysql> select CompanyName,group_concat(CompanyId),count(CompanyId) as count from DemoTable -> group by CompanyName -> having count > 1;
这将生成以下输出 −
+-------------+-------------------------+-------+ | CompanyName | group_concat(CompanyId) | count | +-------------+-------------------------+-------+ | Amazon | 1,5,6 | 3 | | Google | 2,3 | 2 | +-------------+-------------------------+-------+ 2 rows in set (0.00 sec)
广告