2014-09-10 45 views
0

我在摸索着弄清楚爲什麼這兩個刪除結果在sqlite3中是不同的。存在不同的選擇結果?

問題是「如果兩個學生A和B是朋友,並且A喜歡B但不是反之亦然,請從here,Q2中刪除喜歡元組。 (連同actual data

架構爲FriendLikes

.schema Friend 
CREATE TABLE Friend(ID1 int, ID2 int); 

.schema Likes 
CREATE TABLE Friend(ID1 int, ID2 int); 

這兩種方案我想出是:

-- This is correct 
delete from Likes where not exists 
    (select 1 from Likes as l2 where l2.ID1=Likes.ID2 and l2.ID2=Likes.ID1) 
and exists 
    (select 1 from Friend where Likes.ID1=Friend.ID1 and Likes.ID2=Friend.ID2); 

-- Combinng two select into one but this is incorrect 
delete from Likes where not exists 
    (select 1 from Likes as l2, Friend as f where 
     l2.ID1=Likes.ID2 and l2.ID2=Likes.ID1 and 
     Likes.ID1=f.ID1 and Likes.ID2=f.ID2); 

你看,唯一的區別是我把兩個選擇合併爲一個。

不正確的版本是錯誤的,因爲元組(1782,1709)被錯誤地刪除,但它不應該是因爲這個元組不在Friend

回答

1

在正確的查詢中,第一個子查詢使用NOT EXISTS,而第二個子查詢使用EXISTS。 將它們結合是沒有意義的,因爲匹配的Friend行的存在的含義被否定。

相關問題