SQL选择条件:值1<>价值2

时间:2017-11-16 23:40:02

标签: sql if-statement select conditional-statements where

需要您的帮助才能知道是否可以从具有以下条件的表中选择值:

表格内容:2个对象之间的匹配 (Id_obj_A; name_obj_A; country_obj_A; Id_obj_B; name_obj_B; country_obj_B)

Select *
from table
Where (only if country_obj_A <> country_obj_B)

非常感谢你的帮助

1 个答案:

答案 0 :(得分:0)

是。有几种方法,一种是使用NOT EXISTS这样:

select
       *
from tableA
where NOT EXISTS (
   select NULL
   from tableB
   where tableB.country_obj_B = tableA.country_obj_A
   )

或使用NOT IN

select
       *
from tableA
where country_obj_A NOT IN (
   select country_obj_B 
   from tableB
   )

或使用LEFT JOIN然后排除已加入的行:

select
       *
from tableA
left join tableB on tableA.country_obj_A = tableB.country_obj_B
where tableB.country_obj_B IS NULL