MySql查询执行2个表之间的连接

时间:2014-01-30 08:34:23

标签: mysql inner-join

这些是表格:

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

以上是我需要从中检索数据的表。

  

问题是返回同时接受10级和10级的员工名单   第9类。

我写的查询是:

select professor.name 
from inner join works
on professor.empid=works.empid
where works.classid=9 and works.classid=10;

我知道我想要的结果是Arun,但我不知道检索所需结果的确切查询应该是什么。

3 个答案:

答案 0 :(得分:3)

他想要那些取得9级和10级的教授。所以在需要匹配的作品中有2种不同的记录。

select professor.name from  professor
join works A on A.empid=professor.empid and A.classid=9
join works B on B.empid=professor.empid and B.classid=10

请参阅http://sqlfiddle.com/#!2/4be88a/1

答案 1 :(得分:1)

试试这个

select professor.name 
from professor inner join works
on professor.empid=works.empid
where works.classid=9 OR works.classid=10;

(OR)

select professor.name 
from professor inner join works
on professor.empid=works.empid
where works.classid IN ('9','10')

答案 2 :(得分:-1)

SELECT prof.name FROM professor AS prof    
JOIN works     
ON prof.empid = works.empid    
WHERE works.classid IN (9, 10);