如何在单个 MySQL 查询中合并查询,以获取不同列中不同值的计数?
我们首先创建一个表 -
mysql> create table DemoTable760 ( ClientId int, ClientId2 int ); Query OK, 0 rows affected (0.79 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable760 values(300,400); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable760 values(300,400); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable760 values(100,200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable760 values(400,500); Query OK, 1 row affected (0.08 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable760;
这将产生以下输出 -
+----------+-----------+ | ClientId | ClientId2 | +----------+-----------+ | 100 | 200 | | 100 | 200 | | 300 | 400 | | 300 | 400 | | 100 | 200 | | 100 | 200 | | 400 | 500 | +----------+-----------+ 7 rows in set (0.00 sec)
以下查询用于将查询合并到单个查询中,以获取不同列中不同值的计数 -
mysql> select sum(ClientId=100) AS ClientId1,sum(ClientId2=200) AS ClientId2 from DemoTable760;
这将产生以下输出 -
+-----------+-----------+ | ClientId1 | ClientId2 | +-----------+-----------+ | 4 | 4 | +-----------+-----------+ 1 row in set (0.00 sec)
广告