mysql使用having子句连接

时间:2014-01-31 07:28:16

标签: mysql join having

这些是表格:

mysql> select * from professor;
+-------+--------+--------+--------+------+
| empid | name   | status | salary | age  |
+-------+--------+--------+--------+------+
|     1 | Arun   |      1 |   2000 |   23 |
|     2 | Benoy  |      0 |   3000 |   25 |
|     3 | Chacko |      1 |   1000 |   36 |
|     4 | Divin  |      0 |   5000 |   32 |
|     5 | Edwin  |      1 |   2500 |   55 |
|     7 | George |      0 |   1500 |   46 |
+-------+--------+--------+--------+------+
6 rows in set (0.00 sec)

mysql> select * from works;
+----------+-------+---------+
| courseid | empid | classid |
+----------+-------+---------+
|        1 |     1 |      10 |
|        2 |     2 |       9 |
|        3 |     3 |       8 |
|        4 |     4 |      10 |
|        5 |     5 |       9 |
|        6 |     1 |       9 |
|        2 |     3 |      10 |
|        2 |     1 |       7 |
|        2 |     4 |       6 |
|        2 |     5 |       2 |
|        4 |     2 |       6 |
+----------+-------+---------+
11 rows in set (0.00 sec)

mysql> select * from course;
+----------+------------+--------+
| courseid | coursename | points |
+----------+------------+--------+
|        1 | Maths      |    100 |
|        2 | Science    |     80 |
|        3 | English    |     85 |
|        4 | Social     |     90 |
|        5 | Malayalam  |     99 |
|        6 | Arts       |     40 |
|        7 | Biology    |    100 |
+----------+------------+--------+
7 rows in set (0.00 sec)

问题是:

  

返回至少5种不同的课程   员工

我的查询是:

select course.coursename from course
inner join works
on course.courseid=works.courseid
group by works.empid
having count(empid)>=5;

我应该以'科学'为结果。但我得到0结果。请帮助。

1 个答案:

答案 0 :(得分:1)

试试这个

select course.coursename from course
inner join works
on course.courseid=works.courseid
group by course.coursename
having count(Distinct(works.empid))>=5;