如何在单个 MySQL 查询中统计两张表中的行数?
让我们先创建一个表——
mysql> create table DemoTable1 ( Name varchar(40) ); Query OK, 0 rows affected (0.81 sec)
使用 insert 命令在表中插入一些记录——
mysql> insert into DemoTable1 values('Chris'); Query OK, 1 row affected (0.48 sec) mysql> insert into DemoTable1 values('Robert'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1 values('Mike'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录——
mysql> select *from DemoTable1;
它将产生以下输出——
+--------+ | Name | +--------+ | Chris | | Robert | | Mike | +--------+ 3 rows in set (0.00 sec)
以下是创建第二个表的查询——
mysql> create table DemoTable2 ( Score int ); Query OK, 0 rows affected (1.16 sec)
使用 insert 命令在表中插入一些记录——
mysql> insert into DemoTable2 values(86); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable2 values(98); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable2 values(75); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录——
mysql> select *from DemoTable2;
它将产生以下输出——
+-------+ | Score | +-------+ | 86 | | 98 | | 75 | +-------+ 3 rows in set (0.00 sec)
以下是使用一个查询统计两个表中行数的查询——
mysql> select (select count(*) from DemoTable1) AS FirstTableCount, (select count(*) from DemoTable2) AS SecondTableCount from dual;
它将产生以下输出——
+-----------------+------------------+ | FirstTableCount | SecondTableCount | +-----------------+------------------+ | 3 | 3 | +-----------------+------------------+ 1 row in set (0.00 sec)
广告