2014-01-31 70 views
0

這些表:MySQL的加入使用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結果。請幫助。

+4

你爲什麼要通過EMPID分組?對於每個課程,謎題都是你想要計算的 - 所以這就是你應該分組的內容。 – CBroe

+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; 
+0

這應該這樣做,但你可能想添加一個DISTINCT到COUNT – Kickstart

+1

@Kickstart:thanx mate .. :) –