如何在单个MySQL查询中合并查询以获取不同列中不同值的计数?
让我们首先创建一个表-
mysql> create table DemoTable760 ( ClientId int, ClientId2 int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable760 values(100,200); mysql> insert into DemoTable760 values(100,200); mysql> insert into DemoTable760 values(300,400); mysql> insert into DemoTable760 values(300,400); mysql> insert into DemoTable760 values(100,200); mysql> insert into DemoTable760 values(100,200); mysql> insert into DemoTable760 values(400,500);
使用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)