2016-06-28 30 views
3

我被這個問題困住了。考慮下表。我只知道A的價值(即我可以使用類似SELECT * from table WHERE user_one = A的東西)。我試圖做一個自我加入,但沒有幫助。自我加入在這裏沒有幫助。我還可以使用其他什麼方法?

鑑於表

+----------+-----------+---------+ 
| USER_ONE | USER_TWO | STATUS | 
+----------+-----------+---------+ 
|   |   |   | 
| A  | B   | 0  | 
|   |   |   | 
| B  | A   | 1  | 
|   |   |   | 
| A  | C   | 1  | 
|   |   |   | 
| C  | A   | 1  | 
|   |   |   | 
| D  | A   | 1  | 
|   |   |   | 
| A  | E   | 0  | 
+----------+-----------+---------+ 

我期望的結果必須是以下。假設user_one正在關注user_two,如果狀態爲1.狀態0意味着,user_one之前在user_two之後,但現在他取消關注user_two。我需要遵循「A」的用戶。請注意我不想要,他們都跟着彼此像(A -> B)(B -> A)這兩個行都有狀態1.所以對以下響應的問題會是這樣的:「找到我跟隨A的人,但A是不遵循他們「,是有道理的?一點幫助,將不勝感激。

需要的行

+----------+-----------+---------+ 
| USER_ONE | USER_TWO | STATUS | 
+----------+-----------+---------+ 
|   |   |   | 
| B  | A   | 1  | 
|   |   |   | 
| D  | A   | 1  | 
+----------+-----------+---------+ 
+0

一個提示:提供[sqlfiddle](http://sqlfiddle.com/)與樣品datacan增加得到一個(正確的)應答的possibilty。 – FirstOne

+0

@FirstOne,當然,給我幾分鐘 –

回答

2

這應該工作:

使用count(*)

select 
    t1.user_one, 
    t1.user_two, 
    t1.status 
from 
    table t1 
where 
    t1.status = 1 and 
    -- t1.user_two = 'A' and -- If looking for people following user A in specific then uncomment this line 
    (select count(t2.*) 
    from table t2 
    where t2.status = 1 and 
      t2.user_two = t1.user_one and 
      t2.user_one = t1.user_two) = 0 

使用不存在

select 
    t1.user_one, 
    t1.user_two, 
    t1.status 
from 
    table t1 
where 
    t1.status = 1 and 
    -- t1.user_two = 'A' and -- If looking for people following user A in specific then uncomment this line 
    not exists 
     (select 1 
     from table t2 
     where t2.status = 1 and 
       t2.user_two = t1.user_one and 
       t2.user_one = t1.user_two) 
+0

這完美的作品。非常感謝。 –

+1

@ParthapratimNeog很高興能幫到你!請注意,我已經用'not exists'示例更新了我的答案,因爲我發現它的性能比'count(*)']更好(http://stackoverflow.com/q/3271455/2191572) – MonkeyZeus

+0

完全使感。用'not exists'試試看看。 –

2

您可以使用NOT EXISTS此:

SELECT USER_ONE, USER_TWO, STATUS 
FROM mytable AS t1 
WHERE USER_TWO = 'A' AND STATUS = 1 AND 
     NOT EXISTS (SELECT 1 
        FROM mytable AS t2 
        WHERE t2.USER_TWO = t1.USER_TWO AND 
         USER_ONE = 'A' AND STATUS = 1) 
+0

感謝您的答案,出於某種原因,我得到了一個空的答覆。我一定弄亂了列名,我會恢復原狀。 –

相關問題