我正在摸索着为什么这两个删除结果在sqlite3中有所不同。
问题是"如果两个学生A和B是朋友,而A喜欢B但反之亦然,则删除Likes元组。 "来自here,Q2。 (以及actual data)
Friend
和Likes
的架构是
.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
中。
答案 0 :(得分:1)
在正确的查询中,第一个子查询使用NOT EXISTS,而第二个子查询使用EXISTS。
将它们组合起来没有意义,因为匹配Friend
行的存在的含义被否定了。