选择同一个表的另一列中不存在的值,MySQL Database Not Exists Clause

时间:2014-05-20 04:45:38

标签: mysql database exists

我在这里尝试做的是选择 prev_contract_id 列中不存在的所有 contract_id ,并且结束日期早于日期

这是我的数据库表,名为合同,值在 (合同ID 合同类型开始日期结束日期上一个合同ID 员工ID )列

insert into contract values('co-0000001', 'Monthly', '2014-01-01', '2014-02-01','null', 'staff3');
insert into contract values('co-0000002', 'Yearly', '2013-07-07', '2014-07-06','null', 'staff3');
insert into contract values('co-0000003', 'Monthly', '2014-03-20', '2014-04-19','co-0000001', 'staff4');
insert into contract values('co-0000004', 'Yearly', '2014-02-27', '2015-03-27','null', 'staff4');
insert into contract values('co-0000005', 'Ad-hoc', '2014-02-27', '2015-03-27','null', 'staff4');
insert into contract values('co-0000006', 'Yearly', '2013-02-27', '2014-02-27','null', 'staff4');

这是我的SQL语句

select contract_id from contract 
where not exists(select prev_contract_id from contract where prev_contract_id <> 'null') 
and end_date < '2014-05-05';

每个选择语句的结果

select prev_contract_id from contract where prev_contract_id <> 'null';

返回co-0000001 contract_id和

select contract_id from contract where end_date < '2014-05-05';

返回co-0000001co-0000003co-0000006。 我想从选择中删除co-0000001,只返回我0000003和0000006。

当我单独运行它时它起作用,但是当我使用NOT EXISTS子句将它们组合在一起时,我无法得到我的结果。我不想使用IN,因为我听说它更耗时或效率更低。

1 个答案:

答案 0 :(得分:1)

您使用not exists运算符错误。此运算符意味着对于外部select语句中的每一行,都会计算内部select,并且只有在它不返回任何行时才返回外部查询中的行。

如果您检查了您正在使用的内部查询:

select prev_contract_id from contract where prev_contract_id <> 'null'

您将看到它与外部查询无关。由于存在prev_contract_id <> 'null'的行,因此不会返回外部查询中的行。

您遗失的内容是将内部查询与外部查询与contract_id联系起来的附加条件:

SELECT contract_id 
FROM   contract a
WHERE  NOT EXISTS(SELECT prev_contract_id 
                  FROM   contract b
                  WHERE  b.prev_contract_id <> 'null' AND
                         b.prev_contract_id = a.contract_id -- The missing relationship
                 ) AND
       end_date < '2014-05-05';