要针对多个表实现此目的,请使用UNION ALL。
语法如下
select sum(variableName.aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName;
让我们实现以上语法。在这里,我正在使用具有更多表的示例数据库。
我们正在使用的两个表是
用户演示
在哪里
这是显示两个表的所有记录的查询。查询如下所示以显示表“ userdemo”中的记录。
mysql> select *from userdemo;
以下是输出
+--------+----------+------------------+ | UserId | UserName | RegisteredCourse | +--------+----------+------------------+ | 1 | John | Java | | 2 | Larry | C | | 3 | Carol | C++ | | 4 | Mike | C# | +--------+----------+------------------+ 4 rows in set (0.08 sec)
查询如下所示以显示表“ wheredemo”中的记录。
mysql> select *from wheredemo;
以下是输出
+------+---------+ | Id | Name | +------+---------+ | 101 | Maxwell | | 110 | David | | 1000 | Carol | | 1100 | Bob | | 115 | Sam | +------+---------+ 5 rows in set (0.20 sec)
这是从上述两个表中实现count(*)的查询
mysql> select sum(tbl.EachTableCount) -> from -> ( -> select count(*) as EachTableCount from userdemo -> UNION ALL -> select count(*) as EachTableCount from wheredemo -> )tbl;
以下是输出
+-------------------------+ | sum(tbl.EachTableCount) | +-------------------------+ | 9 | +-------------------------+ 1 row in set (0.00 sec)