SELECT t1.deptname AS DEPTNAME,COUNT(1) “没有。员工的” FROM表1 T1 JOIN表2 T2在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>
这并没有2列,只是一个单一的计数取得预期的结果。 – 2012-07-23 09:10:02
我只是告诉方式做这个休息它取决于人多少列他想从表中获得.. – 2012-07-23 09:13:16