排除值SQL

时间:2016-02-22 02:31:07

标签: sql sql-server

SELECT m.name, f.name
FROM   delivered d
JOIN   members m ON d.member_id = m.id
JOIN   members f ON d.friend_member_id = f.id
WHERE  m.shipping_method = f.shipping_method AND
       m.zip_code = f.zip_code

我需要帮助将此连接到名为method的第三个表。上面的friend_member_id将加入此表中的member_id。问题是方法表中的friend_member_id可能有多条记录,我需要排除任何至少有一条记录的friend_member_id,其中type =' express'。基本上,如果是这种情况,friend_member_id在方法表中有任何记录,类型='表达'我不想退回那个名字。

1 个答案:

答案 0 :(得分:1)

使用JOIN

而不是NOT EXISTS
SELECT m.name, f.name
FROM delivered d JOIN
     members m
     ON d.member_id = m.id JOIN
     members f
     ON d.friend_member_id = f.id
WHERE  m.shipping_method = f.shipping_method AND
       m.zip_code = f.zip_code AND
       NOT EXISTS (SELECT 1
                   FROM method mm
                   WHERE mm.member_id = d.friend_member_id AND
                         mm.type = 'express'
                  );