如何在 MySQL 中計算來自多張表的行數?
要在 MySQL 中計算來自多張表的行數,語法如下 −
Select (select count(*) from yourTableName1) as anyAliasName1, (select count(*) from yourTableName2) as anyAliasName2 from dual;
我們先建立一個表 −
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable1 values(),(),(),(),(),(); Query OK, 6 rows affected (0.24 sec) Records: 6 Duplicates: 0 Warnings: 0
使用 select 語句顯示錶中的所有記錄 −
mysql> select * from DemoTable1;
這將產生以下輸出 −
+----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +----+ 6 rows in set (0.00 sec)
以下查詢用於建立第二個表 −
mysql> create table DemoTable2 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable2 values('Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable2 values('David'); Query OK, 1 row affected (0.31 sec)
使用 select 語句顯示錶中的所有記錄 −
mysql> select * from DemoTable2;
這將產生以下輸出 −
+-------+ | Name | +-------+ | Chris | | David | +-------+ 2 rows in set (0.00 sec)
以下是用來計算來自多張表的行數的查詢 −
mysql> select -> (select count(*) from DemoTable1) as FirstTable1Count, -> (select count(*) from DemoTable2) as SecondTable2Count -> from dual;
這將產生以下輸出 −
+---------------------+----------------------+ | FirstTable1Count | SecondTable2Count | +---------------------+----------------------+ | 6 | 2 | +---------------------+----------------------+ 1 row in set (0.00 sec)
廣告