MySQL 查询以计算多张表中的行数


我们首先创建一个表 -

mysql> create table DemoTable1 (FirstName varchar(100));
Query OK, 0 rows affected (0.54 sec)

使用插入命令向表中插入一些记录 -

mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1 values('James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values('David');
Query OK, 1 row affected (0.18 sec)

使用 select 语句从表中显示所有记录 -

mysql> select *from DemoTable1;

这将产生以下输出 -

+-----------+
| FirstName |
+-----------+
| Bob       |
| James     |
| John      |
| David     |
+-----------+
4 rows in set (0.00 sec)

这是创建第二个表的查询 -

mysql> create table DemoTable2 (Marks int);
Query OK, 0 rows affected (0.65 sec)

使用插入命令向表中插入一些记录 -

mysql> insert into DemoTable2 values(98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(89);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable2 values(67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(34);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable2 values(32);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable2 values(42);
Query OK, 1 row affected (0.17 sec)

使用 select 语句从表中显示所有记录 -

mysql> select *from DemoTable2;

这将产生以下输出 -

+-------+
| Marks |
+-------+
| 98    |
| 89    |
| 67    |
| 34    |
| 32    |
| 42    |
+-------+
6 rows in set (0.00 sec)

这是用于计算多张表中行数的查询 -

mysql> select
   (select count(*) from DemoTable1) AS First_Table_Row,
   (select count(*) from DemoTable2) AS Second_Table_Row;

这将产生以下输出 -

+-----------------+------------------+
| First_Table_Row | Second_Table_Row |
+-----------------+------------------+
| 4               | 6                |
+-----------------+------------------+
1 row in set (0.00 sec)

更新于: 22-Aug-2019

940 浏览次数

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告