在MySQL中添加几个COUNT查询的结果?
要添加多个COUNT查询的结果,可以使用以下语法 -
SELECT (SELECT COUNT(*) FROM yourTableName1)+ (SELECT COUNT(*) FROM yourTableName2)+ (SELECT COUNT(*) FROM yourTableName3)+ . . . N AS anyAliasName;
让我们在test数据库中使用三张表 -
- users
- sortingstringdemo
- userlogintable
使用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)
广告