【问题标题】:SQL negation in where clause [duplicate]where子句中的SQL否定[重复]
【发布时间】:2016-07-21 17:01:16
【问题描述】:

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

类:

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

列表:

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

类 id 引用 id_class

我想选择不在列表表中的数据。我试过这个:

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

但没有结果,猜不正确有什么解决办法吗?

【问题讨论】:

  • 试试not innot exists

标签: mysql sql database select negation


【解决方案1】:

你需要一个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)

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 2014-05-03
    • 2012-07-11
    • 1970-01-01
    • 2016-10-06
    • 2012-03-04
    • 2013-05-05
    • 2015-10-15
    • 2017-10-31
    相关资源
    最近更新 更多