如何从一个表中选择不应存在其他记录的记录

时间:2017-03-25 18:50:32

标签: mysql sql

我有两张桌子。 SubjectTbl和SubjectAllotTbl。

这是我的SubjectTbl

+------------+--------------+---------------------+--------------+--------+----------+
| Subject_Id | Subject_Code | Subject_Name        | Periods_Week | Dep_Id | Semester |
+------------+--------------+---------------------+--------------+--------+----------+
|          1 |         6012 | Basic Electronics   |           10 |      1 |        1 |
|          2 |         5412 | Computer Science    |            7 |      1 |        3 |
|          3 |         1421 | Musical Science     |            4 |      1 |        5 |
|          4 |          547 | Network Programming |            7 |      1 |        5 |
+------------+--------------+---------------------+--------------+--------+----------+

和SubjectAllotTbl

+------------+------------+
| Subject_Id | Teacher_Id |
+------------+------------+
|          1 |          1 |
|          2 |          3 |
|          3 |          2 |
+------------+------------+

我想要做的就是从表SubjectTbl中选择Subject_Name,其中SubjectAllotTbl中不应出现相同的subject_id

我正在使用MySql

2 个答案:

答案 0 :(得分:0)

select subject_name
from SubjectTbl
where subject_id not in ( select distinct subject_id from SubjectAllotTbl)

除非subject_id在SubjectAllotTbl中针对不同的teacher_id重复,否则您可能不需要区分

答案 1 :(得分:0)

您可以使用left join执行此操作:所有不加入的行都会在null列上显示SubjectAllotTbl个值,因此您可以对其进行过滤。

select  subject_name
from    SubjectTbl t1
left join
        SubjectAllotTbl t2
on      t1.subject_id = t2.subject_id
where   t2.subject_id is null;