我有两张桌子。一个是Course
表,第二个是Teacher
表。我希望得到所有Teacher
不教'Math'
的人。我怎么能这样做?
课程表
course_id course teacher_id marks
1 Physics 1 60
2 Math 1 60
3 Chemestry 1 60
4 English 2 60
5 Hindi 2 60
6 Physics 2 60
7 Chemestry 3 60
8 English 4 60
9 Math 5 60
10 Math 6 60
教师表
teacher_id name salary gender
1 Teacher1 20 1
2 Teacher2 30 1
3 Teacher3 40 2
4 Teacher4 50 2
5 Teacher5 60 1
6 Teacher6 70 2
答案 0 :(得分:1)
我希望得到所有不教数学的老师。
您需要加入 teacher_id 上的两个表格,然后根据课程过滤掉这些行。
SQL> SELECT DISTINCT t.name
2 FROM course c,
3 teacher t
4 WHERE c.teacher_id = t.teacher_id
5 AND c.course <> 'Math';
NAME
--------
Teacher2
Teacher1
Teacher4
Teacher3
SQL>
编辑由于您有老师教授多门课程,您需要进一步过滤:
SQL> WITH DATA AS
2 (SELECT c.*,
3 t.name
4 FROM course c,
5 teacher t
6 WHERE c.teacher_id = t.teacher_id
7 AND c.course <> 'Math'
8 )
9 SELECT DISTINCT name
10 FROM data
11 WHERE teacher_id NOT IN
12 (SELECT teacher_id FROM course WHERE course = 'Math'
13 )
14 /
NAME
--------
Teacher2
Teacher4
Teacher3
SQL>
注意请注意,使用 NOT EXISTS 子句的其他解决方案在性能方面更好,因为表扫描较少甚至是索引扫描。使用适当的索引,不存在的查询将是一种最佳方法。
答案 1 :(得分:1)
select *
from teacher t
where not exists
(select 1 from course c where c.teacher_id = t.teacher_id and c.course = 'Math')
@LalitKumarB 本是绝对正确的
答案 2 :(得分:0)
内部联接
select t.teacher_id, t.name
from teacher t, Course c
where c.course='math' and t.teacher_id=c.teacher_id;
修改强>
你可以使用join和subquery来做。
select * from course join teacher
on course.teacher_id=teacher.teacher_id
where teacher.teacher_id not in
(select distinct teacher_id from course where course = 'Math')
答案 3 :(得分:-1)
Select * from Teacher
join Course
on Teacher.teacher.id = Course.teacher.id
where Course.course != 'Math'
答案 4 :(得分:-1)
select
t.name
from teacher t
left join course c
on c.teacher_id = t.teacher_id
where c.course_id <> 2