正确使用NOT EXISTS

时间:2015-04-12 04:17:17

标签: sql sql-server subquery filtering exists

我有两张桌子 -

member_master
-----------------------------
member_id, ( PK )
branch_id, ( PK )
name member_id, 


member_photo 
-----------------------------
member_id, ( FK )
branch_id, ( FK )
photo_index, 
photo_file

member_master中的每个条目在member_photo表中都有零个或多个相应的条目。

我有两个要求:

  1. 从member_master获取所有在member_photo表中至少有一个条目的条目。我使用以下SQL命令

    获得了正确的结果
    SELECT DISTINCT member_master.member_id,member_master.branch_id,name
     FROM member_master, member_photo
     WHERE member_master.branch_id=1 
     AND EXISTS
     (
       SELECT member_photo.member_id 
       WHERE member_master.member_id = member_photo.member_id 
       AND member_master.branch_id = member_photo.branch_id
     )
    ;
    
  2. member_master获取member_photo表中没有任何条目的所有条目。我使用以下SQL命令

    SELECT DISTINCT member_master.member_id,member_master.branch_id,name FROM member_master, member_photo
    WHERE member_master.branch_id=1 
    AND NOT EXISTS
    (
      SELECT member_photo.member_id 
      WHERE member_master.member_id = member_photo.member_id 
      AND member_master.branch_id = member_photo.branch_id
    )
    ;
    
  3. 唯一的区别是我在EXISTS命令之前添加了NOT。 但不幸的是,它没有给我正确的结果。它只返回表中的所有行。

    请注意我使用的是SQL Server Express 2005。

2 个答案:

答案 0 :(得分:0)

你应该在不加入表的情况下进行,只需从主表中选择并添加照片表的检查,如下所示:

SELECT
  m.member_id,
  m.branch_id,
  m.name 
FROM 
  member_master m
WHERE 
  m.branch_id=1 AND 
  EXISTS (SELECT 1 from member_photo p where
    m.member_id = p.member_id AND m.branch_id = p.branch_id)

与其他情况类似:

SELECT
  m.member_id,
  m.branch_id,
  m.name 
FROM 
  member_master m
WHERE 
  m.branch_id=1 AND 
  not EXISTS (SELECT 1 from member_photo p where
    m.member_id = p.member_id AND m.branch_id = p.branch_id)

答案 1 :(得分:0)

必需的SQL查询是:

SELECT 
      member_id,
      branch_id,
      name 
FROM member_master
WHERE member_master.branch_id=1
    AND NOT EXISTS(SELECT member_photo.member_id 
                   WHERE member_master.member_id = member_photo.member_id
                       AND member_master.branch_id = member_photo.branch_id)