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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP