要计算MySQL中多个表中的行,语法如下-
Select (select count(*) from yourTableName1) as anyAliasName1, (select count(*) from yourTableName2) as anyAliasName2 from dual;
让我们首先创建一个表-
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(),(),(),(),(),(); Records: 6 Duplicates: 0 Warnings: 0
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1;
这将产生以下输出-
+----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +----+ 6 rows in set (0.00 sec)
以下是创建第二个表的查询-
mysql> create table DemoTable2 -> ( -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values('Chris'); mysql> insert into DemoTable2 values('David');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable2;
这将产生以下输出-
+-------+ | Name | +-------+ | Chris | | David | +-------+ 2 rows in set (0.00 sec)
以下是对来自多个表的行进行计数的查询-
mysql> select -> (select count(*) from DemoTable1) as FirstTable1Count, -> (select count(*) from DemoTable2) as SecondTable2Count -> from dual;
这将产生以下输出-
+---------------------+----------------------+ | FirstTable1Count | SecondTable2Count | +---------------------+----------------------+ | 6 | 2 | +---------------------+----------------------+ 1 row in set (0.00 sec)