选择不在具有额外Where条件的另一个表中的元素

时间:2018-04-16 20:56:23

标签: mysql

tl:dr 此命令不起作用:(

SELECT * FROM homework WHERE crn =138628 AND WHERE id NOT IN (SELECT id FROM studentHw WHERE codigoAlumno="214521671");

对不起西班牙名字

我想比较两个表来查找另一个表中没有的id。我有两张桌子:

家庭作业表:带有组代码(crn)和id(识别作业)

+------------+------------+--------+-----+
| titulo     | fecha      | crn    | id  |
+------------+------------+--------+-----+
| Tarea 1    | 2018-03-14 | 138628 |  25 |
| Tarea 2    | 2018-03-14 | 138628 | 158 |
| Tarea 3    | 2018-03-14 | 138628 | 159 |
| Tarea 1    | 2018-03-15 | 125488 | 162 |
| Tarea 2    | 2018-03-15 | 125488 | 163 |
+------------+------------+--------+-----+



SELECT * FROM homework ;

我想只选择crn等于138628的元素,并将它与另一个名为studentHW的表格(交付作业)进行比较后:

studentHW

+-----+--------------+---------+--------+
| id  | codigoAlumno | entrega | crn    |
+-----+--------------+---------+--------+
| 25  | 214521671    | si      | 138628 |
| 158 | 214521671    | si      | 138628 |
| 159 | 214521671    | si      | 138628 |
+-----+--------------+---------+--------+

SELECT * FROM studentHw;

我想选择Homework中不在studentHomework

中的所有行

我在stackoverflow中检查我找到的答案......

Mysql: Select rows from a table that are not in another

我尝试使用以下命令,但它不起作用:

SELECT * FROM homework WHERE crn =138628 AND WHERE id NOT IN (SELECT id FROM studentHw WHERE codigoAlumno="214521671");

codigoalumno是学生ID

我收到此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id NOT IN (SELECT id FROM studentHw)' at line 1

1 个答案:

答案 0 :(得分:1)

WHERE关键字只能在查询中使用一次。

正确的代码:

SELECT * FROM homework WHERE crn =138628 AND id NOT IN (SELECT id FROM studentHw WHERE codigoAlumno="214521671");