sql not exists的使用

一.使用原因

一般我们在做不包含的时候使用not in 就可以了,可是很多时候做join表关联的,没有一个主键,都是二三个字段才能确定一条数据,所以在做不包含用notin 就无法实现了
在这里插入图片描述
一般sql select * from b where (aaa,bbb) in ( select aaa,bbb from a );
现在就要需要一个条件可以使用多个条件关联not in 怎么办呢?

二.exists使用

sql not exists的使用_第1张图片

SELECT  [Id]
      ,[Name]
      ,[Value]
      ,[OperateTime]
      ,[OperateUser]
      ,[SysRemark]
      ,[SC]
      ,[PG]
      ,[PGNODE]
      ,[PA]
      ,[PANODE]
      ,[ME]
      ,[MENODE]
  FROM [OpcenterRDnL].[dbo].[TB_ELNLOG] a
    where not exists(
     SELECT*
  FROM [OpcenterRDnL].[dbo].[TB_ELNLOG] b where  b.Value=N'已审核' and  a.SC
  =b.SC and a.PG=b.PG and a.PA =b.PA
   )

sql not exists的使用_第2张图片
多字段关联就可以实现效果

三.总结

   多字段in、not in在db2数据中可以执行,SQL Server不行。

   exists、not exists在db2,SQL Server均可执行。

   而且总体上用exists,not exists 效率都很高,建议大家还是用好exists,not exists

你可能感兴趣的:(sql)