SQL集差异

时间:2015-01-15 21:52:42

标签: mysql sql

我如何在SQL中执行以下操作:

select distinct(territory_id) from main_territorypricing

"minus"

select distinct(territory_id) from main_territorypricing where store_url is not null

基本上,我希望第一行中包含的所有territory_id都不包含在第二行中。

2 个答案:

答案 0 :(得分:7)

如果你想按照你说的那样做:

select distinct territory_id 
from main_territorypricing
where territory_id not in (
    select territory_id from main_territorypricing where store_url is not null
    )

但基于您所描述的逻辑,更简单的解决方案是:

select territory_id 
    from main_territorypricing
    where store_url is null

如果您只有这两个字段(territory_id和store_url)并且行是唯一的,那么这就是。

否则,还有另一个棘手的解决方案:

select territory_id 
from main_territorypricing
group by territory_id 
having (max(store_url) is null)

答案 1 :(得分:0)

select distinct(territory_id) from main_territorypricing
where
    territory_id in
      (select territory_id from main_territorypricing)
and territory_id not in 
    (select territory_id from main_territorypricing where store_url is not null)