一個查詢來獲取 MySQL 中不同表中的計數總和?
要獲取不同表的計數總和,請使用 UNION ALL。讓我們首先建立一個表 -
mysql> create table DemoTable1 -> ( -> Id int, -> Name varchar(30) -> ); Query OK, 0 rows affected (1.55 sec)
使用插入命令在表中插入一些記錄 -
mysql> insert into DemoTable1 values(10,'Chris Brown'); Query OK, 1 row affected (0.83 sec) mysql> insert into DemoTable1 values(20,'David Miller'); Query OK, 1 row affected (0.50 sec) mysql> insert into DemoTable1 values(30,'John Adam'); Query OK, 1 row affected (0.83 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select *from DemoTable1;
輸出
+------+--------------+ | Id | Name | +------+--------------+ | 10 | Chris Brown | | 20 | David Miller | | 30 | John Adam | +------+--------------+ 3 rows in set (0.00 sec)
以下是建立第二個表的查詢 -
mysql> create table DemoTable2 -> ( -> Amount int -> ); Query OK, 0 rows affected (1.17 sec)
使用插入命令在表中插入一些記錄 -
mysql> insert into DemoTable2 values(100); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable2 values(200); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(300); Query OK, 1 row affected (0.54 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select *from DemoTable2;
輸出
+--------+ | Amount | +--------+ | 100 | | 200 | | 300 | +--------+ 3 rows in set (0.00 sec)
以下是如何在一個查詢中獲取不同表的計數總和 -
mysql> select sum(AllCount) AS Total_Count -> from -> ( -> (select count(*) AS AllCount from DemoTable1) -> union all -> (select count(*) AS AllCount from DemoTable2) -> )t;
輸出
+-------------+ | Total_Count | +-------------+ | 6 | +-------------+ 1 row in set (0.03 sec)
廣告