如何對 MySQL union 查詢進行計數?


要對 union 進行計數,即進行 UNION 結果的計數,請使用以下語法 −

SELECT COUNT(*)
FROM
(
SELECT yourColumName1 from yourTableName1
UNION
SELECT yourColumName1 from yourTableName2
) anyVariableName;

為了理解以上語法,讓我們建立兩個有記錄的表。建立表的查詢如下 −

mysql> create table union_Table1
-> (
-> UserId int
-> );
Query OK, 0 rows affected (0.47 sec)

使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into union_Table1 values(1);
Query OK, 1 row affected (0.18 sec)

mysql> insert into union_Table1 values(10);
Query OK, 1 row affected (0.12 sec)

mysql> insert into union_Table1 values(20);
Query OK, 1 row affected (0.09 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from union_Table1;

以下是輸出 −

+--------+
| UserId |
+--------+
| 1      |
| 10     |
| 20     |
+--------+
3 rows in set (0.00 sec)

建立第二個表的查詢。

mysql> create table union_Table2
-> (
-> UserId int
-> );
Query OK, 0 rows affected (0.69 sec)

使用 insert 命令在表中插入記錄。查詢如下。

mysql> insert into union_Table2 values(1);
Query OK, 1 row affected (0.12 sec)

mysql> insert into union_Table2 values(30);
Query OK, 1 row affected (0.26 sec)

mysql> insert into union_Table2 values(50);
Query OK, 1 row affected (0.13 sec)

使用 select 命令顯示錶中的所有記錄。查詢如下 −

mysql> select *from union_Table2;

以下是輸出 −

+--------+
| UserId |
+--------+
| 1      |
| 30     |
| 50     |
+--------+
3 rows in set (0.00 sec)

在這兩個表中,如果任何記錄都相同,則它將只被考慮一次。以下是 union 中的計數查詢。

mysql> select count(*) as UnionCount from
-> (
-> select distinct UserId from union_Table1
-> union
-> select distinct UserId from union_Table2
-> )tbl1;

以下是顯示計數的輸出。

+------------+
| UnionCount |
+------------+
| 5          |
+------------+
1 row in set (0.00 sec)

更新於: 25-6-2020

6 千+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.