2014-01-31 101 views
0

使用組這些都是我的表MySQL的加入通過

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 | 
    +-------+--------+--------+--------+------+ 
    5 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 | 
|  4 |  2 |  6 | 
|  7 |  5 |  6 | 
|  3 |  5 |  2 | 
|  2 |  4 |  6 | 
|  2 |  5 |  2 | 
+----------+-------+---------+ 
15 rows in set (0.00 sec) 

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

的問題是:

Return the names of full professors who have taught at least two courses in one Class 

我的查詢是:

select professor.name from professor 
inner join works 
on professor.empid=works.empid 
group by works.empid 
having count(distinct works.courseid)>=2 

我現在得到的輸出繼電器是:

Arun 
Benoy 
Chacko 
Divin 
Edwin 

我被認爲是'Edwin'的輸出,因爲他是唯一一個在同一班上教過兩門科目的人。請幫助

回答

2

你必須考慮你的小組是錯改變這個

group by classid,works.empid 

一樣,你會在數CLASSID courseid。

+0

謝謝。這工作:)我真的很糟糕的做羣查詢。你能告訴mw真的是哪個團體嗎? –

+1

歡迎老兄:):group by是將結果集合成一列或多列。在你的情況下,你由classid分組,然後由empid分組。 –

+0

我從來沒有理解過使用2列的想法。猜我會更多的時候學習更多:) –