获取具有条件的唯一行的SQL语句

时间:2014-04-16 13:04:08

标签: mysql sql

我正在开发一个Web应用程序,并且在出现可以检索的SQL语句时遇到了问题,
1)记录SenderID不能是UserThree
2)记录ReceiverID不能是UserThree
3)在SenderID中没有UserTwo的记录,因为我想要检索的是没有任何"链接的记录。使用UserThree之前。在这种情况下,UserTwo与第2行中的UserThree绑定,因此我需要使用UserTwo过滤掉所有记录作为SenderID。

我所拥有的只是" UserThree"作为在SQL语句的条件中使用的ID。  这是我现在的SQL语句

SELECT * FROM user WHERE senderID != "UserThree" AND receiverID != "UserThree";

满足前两个条件而不是第三个条件。

以下是一个例子

SenderID       ReceiverID
-------------------------
1)UserOne        UserTwo
2)UserTwo        UserThree
3)UserTwo        UserFour
4)UserTwo        UserFive
5)UserFour       UserSix
6)UserFour       UserSeven

我想要得到的是,

SenderID       ReceiverID
-------------------------
1)UserOne        UserTwo
5)UserFour       UserSix
6)UserFour       UserSever

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT * FROM user 
WHERE 
(senderID NOT IN (SELECT senderID FROM user u1 where u1.ReceiverID = "UserThree"))
AND
(ReceiverID NOT IN (SELECT ReceiverID FROM user u2 where u2.senderID = "UserThree"));

使用此查询将不包括连接到UserThree的所有记录(包括UserThree作为发送方和接收方)

如果您只需要过滤使用senderID的连接:

SELECT * FROM user 
WHERE 
senderID != "UserThree"
AND
(senderID NOT IN (SELECT senderID FROM user u1 where u1.ReceiverID = "UserThree"));