SELECT t1.deptname AS deptname, COUNT(1) AS "no. of employees" FROM table1 t1 JOIN table2 t2 ON t2.deptno = t1.deptno GROUP BY t1.deptno;
您可以通过执行以下操作重新创建它:
mysql>
mysql> CREATE TABLE table1 (deptno INT NOT NULL, deptname VARCHAR(24) NOT NULL, PRIMARY KEY (deptno));
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE table2 (empid INT NOT NULL, empname VARCHAR(48) NOT NULL, sal VARCHAR(16), deptno INT);
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO table1 VALUES (101, "sales"), (102, "hr"), (103, "finance");
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> INSERT INTO table2 VALUES (1, "John", "1500$", 101);
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO table2 VALUES (2, "Kevin", "1200$", 101), (3, "James", "1000$", 101);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> INSERT INTO table2 VALUES (4, "Ford", "700$", 102), (5, "David", "855$", 102), (6, "George", "955$", 103);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT t1.deptname AS deptname, COUNT(1) AS "no. of employees" FROM table1 t1 JOIN table2 t2 ON t2.deptno = t1.deptno GROUP BY t1.deptno;
+----------+------------------+
| deptname | no. of employees |
+----------+------------------+
| sales | 3 |
| hr | 2 |
| finance | 1 |
+----------+------------------+
3 rows in set (0.00 sec)
mysql>