SQL where 子句中的否定

SQL negation in where clause

您好,我正在尝试解决否定数据的问题,我有两个 table

类:

+----+----------+--+
| id |   name   |  |
+----+----------+--+
|  1 | 'First'  |  |
|  2 | 'Second' |  |
+----+----------+--+

列表:

+----+----------+--+
| id | id_class |  |
+----+----------+--+
|  1 |        1 |  |
+----+----------+--+

class id 引用 id_class

我想 select 列表中没有的数据 table。我试过这个:

  SELECT c.name FROM classes c JOIN lists l ON (l.id_class=c.id) WHERE l.id_class!=c.id 

但是没有结果,估计不对 有解决办法吗?

你需要 LEFT JOIN:

SELECT c.id, c.name
from classes c 
left join lists l on (l.id_class=c.id) 
where l.id_class is null

或者,您也可以使用 NOT EXISTS:

select c.id, c.name
from classes c 
where not exists (select *
                  from lists l
                  where l.id_class=c.id)