MySQL 是否从多张表中计数 (*)?
要实现此功能以应用于多张表,可以使用 UNION ALL。
语法如下:
select sum(variableName.aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName;
让我们实现上述语法。此处,我使用具有更多表的示例数据库。
我们使用的两张表是:
- userdemo
- wheredemo
以下是用于显示两张表中所有记录的查询。以下是用于显示表 “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)
广告