SQL中的多列的NOT IN子句

时间:2015-01-14 06:59:32

标签: mysql sql

我有一个SQL查询:

select * from  product_structure_resources 
where resource_id NOT IN (select resource_id from resources);

现在我需要在where子句之后添加像branch_id和scheme_id这样的列。

喜欢:

select * from  product_structure_resources 
where resource_id,scheme_id,branch_id NOT IN (select resource_id from resources);

我该怎么办?

P.S:资源表中没有scheme_id和branch_id列。它只有resource_id列。

3 个答案:

答案 0 :(得分:0)

select * 
from  product_structure_resources pr
where not exists (select 1 from resources r where pr.resource_id = r.resource_id)
and not exists (select 1 from resources r where pr.scheme_id= r.resource_id)
and not exists (select 1 from resources r where pr.branch_id= r.resource_id)

答案 1 :(得分:0)

这应该返回与juergen d's query完全相同的结果。

SELECT psr.*
FROM product_structure_resources AS psr
LEFT JOIN resources AS r ON r.resource_id = psr.resource_id)
LEFT JOIN resources AS s ON s.resource_id = psr.scheme_id)
LEFT JOIN resources AS b ON b.resource_id = psr.branch_id)
WHERE r.resource_id IS NULL
AND s.resource_id IS NULL
AND b.resource_id IS NULL

只是为了好玩,还有这种极端(模糊和不明智的)方式:

SELECT *
FROM product_structure_resources AS psr
WHERE resource_id IN (
    SELECT resources.resource_id FROM resources
    WHERE resources.resource_id NOT IN (psr.resource_id, psr.scheme_id, psr.branch_id)
)

答案 2 :(得分:-1)

我认为它可能有用并且可以帮助你

select *
from  product_structure_resources 
where concat(resource_id,scheme_id,branch_id) NOT IN
(select concat(resource_id,scheme_id,branch_id) from resources);

投票,如果它可以帮助你