要计算来自单独表的值,语法如下:
Select ( select count(yourColumnName) from yourTableName1) as anyAliasName1, ( select count(yourColumnName) from yourTableName2) as anyAliasName2;
让我们首先创建一个表-
mysql> create table DemoTable1 -> ( -> Id int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(1); mysql> insert into DemoTable1 values(NULL); mysql> insert into DemoTable1 values(2); mysql> insert into DemoTable1 values(3);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1;
这将产生以下输出-
+------+ | Id | +------+ | 1 | | NULL | | 2 | | 3 | +------+ 4 rows in set (0.00 sec)
以下是创建第二个表的查询-
mysql> create table DemoTable2 -> ( -> Id int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values(10); mysql> insert into DemoTable2 values(NULL); mysql> insert into DemoTable2 values(NULL);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable2;
这将产生以下输出-
+------+ | Id | +------+ | 10 | | NULL | | NULL | +------+ 3 rows in set (0.00 sec)
这是从单独的表中获取计数的查询-
mysql> select -> ( -> select count(Id) from DemoTable1) as CountFirstTableId, -> ( -> select count(Id) from DemoTable2) as CountSecondTableId -> ;
这将产生以下输出-
+-------------------+--------------------+ | CountFirstTableId | CountSecondTableId | +-------------------+--------------------+ | 3 | 1 | +-------------------+--------------------+ 1 row in set (0.00 sec)