Php Mysql - 获取表中不存在的结果取决于另一个表

时间:2014-08-24 06:02:51

标签: php mysql

我有两张桌子

Students table:
+----------+---------+
|Student Id|  Name   |
+----------+---------+
|  11      |  Jack   |
+----------+---------+
|  30      |  Tom    |
+----------+---------+
|  35      |  David  |
+----------+---------+
|  66      |  Mia    |
+----------+---------+
|  90      |  Daniel |
+----------+---------+
|  100     |  Steve  |
+----------+---------+

Student_course_number table :
+--------+------------+--------------+
|  ID    |Student Id  |course number |
+--------+------------+--------------+
|  1     |  66        | 102          |
+--------+------------+--------------+
|  2     |  66        | 103          |
+--------+------------+--------------+
|  3     |  66        | 40           |
+--------+------------+--------------+
|  4     |  66        | 41           |
+--------+------------+--------------+
|  5     |  30        | 55           |
+--------+------------+--------------+
|  6     |  30        | 103          |
+--------+------------+--------------+
|  7     |  35        | 40           |
+--------+------------+--------------+
|  8     |  35        | 41           |
+--------+------------+--------------+
|  9     |  90        | 55           |
+--------+------------+--------------+
|  10    |  90        | 100          |
+--------+------------+--------------+
|  11    |  11        | 40           |
+--------+------------+--------------+
|  12    |  11        | 41           |
+--------+------------+--------------+
|  13    |  11        | 55           |
+--------+------------+--------------+
I would like to get the following output:
Student DID NOT participate in the course number 103

+-----------+----------+
|Student Id |  Name    |
+-----------+----------+
|  11       |  Jack    |
+-----------+----------+
|  35       |  David   |
+-----------+----------+
|  90       |  Daniel  |
+-----------+----------+
|  100      |  Steve   |
+-----------+----------+

  • 有些学生没有参加任何课程。

2 个答案:

答案 0 :(得分:2)

您需要使用Left Outer Join来获取学生中存在的所有记录,而不是int course

SELECT * FROM Students 
LEFT OUTER JOIN Student_course_number 
ON Students.Student_Id = Student_course_number.Student_Id
WHERE Student_course_number.ID IS null

答案 1 :(得分:1)

您可以使用not in运算符:

SELECT * 
FROM   students
WHERE  student_id NOT IN (SELECT student_id
                          FROM   student_course_number
                          WHERE  course_number = 103)