要添加来自多个COUNT查询的结果,可以使用以下语法-
SELECT (SELECT COUNT(*) FROM yourTableName1)+ (SELECT COUNT(*) FROM yourTableName2)+ (SELECT COUNT(*) FROM yourTableName3)+ . . . N AS anyAliasName;
让我们在测试数据库中使用三个表-
使用者
排序字符串演示
用户可登录
使用select语句从表中检查表记录。让我们带记录的3个示例表。
第一个表的表记录如下-
mysql> select *from users;
以下是输出-
+----+----------+---------------------+ | Id | UserName | UserLastseen | +----+----------+---------------------+ | 1 | Larry | 2019-01-15 02:45:00 | | 2 | Sam | 2019-01-15 15:01:52 | | 3 | Mike | 2019-01-15 02:30:00 | | 4 | Bob | 2019-01-15 15:02:00 | | 5 | David | 2019-01-15 14:55:00 | +----+----------+---------------------+ 5 rows in set (0.08 sec)
第二表记录如下-
mysql> select *from sortingstringdemo;
以下是输出-
+--------+ | Amount | +--------+ | 12.34 | | 124.50 | | 9.59 | | 150.68 | | 600.54 | +--------+ 5 rows in set (0.06 sec)
第三表记录如下-
mysql> select *from userlogintable;
以下是输出-
+----+--------+---------------------+ | Id | UserId | UserLoginDateTime | +----+--------+---------------------+ | 1 | 2 | 2019-01-27 13:47:20 | | 3 | 2 | 2019-01-26 11:30:30 | | 4 | 1 | 2015-03-11 15:23:55 | +----+--------+---------------------+ 3 rows in set (0.18 sec)
应用上面讨论的语法以添加来自多个COUNT查询的结果。
在下面的查询中,我应用了以上三个表名-
mysql> select (select count(*) from users) -> +(select count(*) from sortingstringdemo) -> +(select count(*) from userlogintable) as TotalRecords;
以下是显示所有三个表的记录计数的输出-
+--------------+ | TotalRecords | +--------------+ | 13 | +--------------+ 1 row in set (0.00 sec)