1

我有这个问题要解决:如果两个学生 A 和 B 是朋友,并且 A 喜欢 B 但反之不喜欢,请删除 Likes 条目

对于背景,Friend 表有两列,STU1 和 STU2。如果他们是朋友,那么会有一个条目显示 STU1、STU2 和 STU2、STU1。

在 Likes 表中,如果学生 A 喜欢学生 B,则会有 STU1、STU2 的条目,但如果学生 B 不喜欢学生 A,则不会有 STU2、STU1 的条目。

所以,这就是我尝试过的。问题是它仍然在 Likes 表中留下了两行应该不存在的行。关于如何解决这个问题的任何想法?

delete from Likes
where exists 
    (select F.STU1, F.STU2 from Friend F
        where exists  
        (select L.STU1, L.STU2 from Likes L, Friend F where
            F.STU1 = L.STU1 and F.STU2 = L.STU2)
        )
    and not exists
        (select L.STU1, L.STU2 from Likes L, Friend F where
            F.STU1 = L.STU2 and F.STU2 = L.STU1)
4

2 回答 2

0

编辑:

with onewayfriends as (
select f.* from friend f
left outer join likes l1 on l1.stu1=f.stu1 and l1.stu2=f.stu2
left outer join likes l2 on l2.stu1=f.stu2 and l2.stu2=f.stu1
where l1.stu1 is null or l2.stu1 is null)

delete l from likes l, onewayfriends f
where l.stu1 in (f.stu1, f.stu2) and l.stu2 in (f.stu1, f.stu2)

编辑 2,因为它是 sqllite 将 cte 重写为嵌套查询,并将带有 join 的删除重写为 'where row id in..'

delete from likes where rowid in (select l.rowid from
(
  select f.* from friend f
  left outer join likes l1 on l1.stu1=f.stu1 and l1.stu2=f.stu2
  left outer join likes l2 on l2.stu1=f.stu2 and l2.stu2=f.stu1
  where l1.stu1 is null or l2.stu1 is null
) f, likes l
where l.stu1 in (f.stu1, f.stu2) and l.stu2 in (f.stu1, f.stu2))

小提琴

于 2013-01-29T22:52:58.770 回答
0

你说 Friend 表有两对。因此,我们需要从 Likes 表中删除该对在 Friend 表中的对,但在 Likes 表中不存在反对。

DELETE
FROM Likes
WHERE EXISTS (SELECT 1 FROM Friend f WHERE Likes.STU1 = f.STU1 AND Likes.STU2 = f.STU2)
  AND NOT EXISTS (SELECT 1 FROM Likes ml WHERE Likes.STU1 = ml.STU2 AND Likes.STU2 = ml.STU1)
于 2013-01-30T01:50:29.613 回答