2014-01-30 195 views
2

這些都是表:MySQL查詢聯接和子查詢

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

course: 
+----------+------------+--------+ 
| courseid | coursename | points | 
+----------+------------+--------+ 
|  1 | Maths  | 100 | 
|  2 | Science |  80 | 
|  3 | English |  85 | 
|  4 | Social  |  90 | 
|  5 | Malayalam |  99 | 
|  6 | Arts  |  40 | 
+----------+------------+--------+ 

的問題是:誰教課程數學或科學,但 不能同時

員工

返回列表

我寫的查詢是:

select distinct professor.name from professor 
inner join works 
on professor.empid=works.empid 
where works.courseid in 
(select courseid from course where coursename ='Maths' or coursename='Science'); 

我收到的輸出是:

Arun 
Benoy 
Chacko 

這裏的員工「阿倫」不應該被顯示爲他的教導兩個數學和科學。

請幫我一把!

回答

3

您可以使用總計COUNT()來檢查教授的DISTINCT課程的總數是否恰好爲1,同時仍過濾到兩種不同類型的課程。這確保只有一個,從來沒有兩個,都返回。

由於IN()限制最初只返回到兩個所需課程的所有行,教授可以通過COUNT(DISTINCT coursename)最多有2個可能的不同課程。 A HAVING子句然後禁止那些最終結果集中包含2的子句。

SELECT 
    DISTINCT professor.name 
FROM 
    professor 
    INNER JOIN works ON professor.empid = works.empid 
    /* Join against course to get the course names */ 
    INNER JOIN course ON works.courseid = course.courseid 
WHERE 
    /* Restrict only to Maths, Science */ 
    course.coursename IN ('Maths', 'Science') 
GROUP BY professor.name 
/* Only those with exactly one type of course */ 
HAVING COUNT(DISTINCT course.coursename) = 1 

這裏是一個演示:http://sqlfiddle.com/#!2/2e9610/2

0

您想在這裏使用一個xor而不是or的。

select distinct professor.name from professor 
inner join works 
on professor.empid=works.empid 
where works.courseid in 
(select courseid from course where coursename ='Maths' xor coursename='Science');