简体   繁体   中英

SQL statement in getting unique rows with conditions

I'm working on a web app and have faced a problem in coming out with an SQL statement that could retrieve,
1) Records that SenderID cannot be UserThree
2) Records that ReceiverID cannot be UserThree
3) Records that does not have UserTwo in the SenderID, as what I wanted to retrieve is records that does not have any "linkage" with UserThree before. In this case, UserTwo is tied to UserThree in Row 2, thus I will need to filter out all records with UserTwo as the SenderID.

What I have is only "UserThree" as the ID to be use in the condition of the SQL statement. Here's the SQL statement I have now

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

Which fulfilled the first two condition but not the third.

Below is an example

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

And what I'm trying to get is,

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

try:

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"));

with this query all records connected to UserThree (including UserThree as both sender and receiver) will not be included

if you need to only filter connections for senderID use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM