我正在从斯坦福DB课程中解决问题并提出问题。我有2张桌子。第一个表有2个字段,所以我们有T1(ID1,ID2)。第二个表有更多列。
如果我这样做
select T1.ID1, T1.ID2
from T1, T2 as X, T2 as Y, T2 as Z
where <condition>
except
select T1.ID2, T1.ID1
from T1, T2 as X, T2 as Y, T2 as Z
where <different condition>;
然后我得到2个元组
A1 | B1
A2 | B2
结果是。这正是我所期待的。
问题是如何使用这些元组从T1中删除行?
我试过
delete
from T1
where ID1=(<select from above using only the first variable in the select>)
and ID2=(<select from above using only the second variable in the select>);
这不起作用,我没有办法做到这一点。 有线索吗? 感谢
答案 0 :(得分:0)
DELETE FROM t1
inner join T2 ON t1.ID1 = t2.ID1 AND t1.ID2 = t2.ID2
答案 1 :(得分:0)
不确定这是否可以在SQLite中使用,但您可以尝试一下:
DELETE FROM T1
WHERE EXISTS (
SELECT *
FROM (
select T1.ID1, T1.ID2
from T1, T2 as X, T2 as Y, T2 as Z
where <condition>
except
select T1.ID2, T1.ID1
from T1, T2 as X, T2 as Y, T2 as Z
where <different condition>
) s
WHERE s.ID1 = T1.ID1
AND s.ID2 = T1.ID2
)
这可能是次优的,也许你可以改为拆分你的EXCEPT查询:
DELETE FROM T1
WHERE EXISTS (
/* slightly modified left part of the EXCEPT query */
select T1.ID1, T1.ID2
from T1 AS T1_, T2 as X, T2 as Y, T2 as Z
where <condition>
AND T1_.ID1 = T1.ID1
AND T1_.ID2 = T1.ID2
)
AND NOT EXISTS (
/* slightly modified right part of the EXCEPT query */
select T1.ID2, T1.ID1
from T1 AS T1_, T2 as X, T2 as Y, T2 as Z
where <different condition>
AND T1_.ID2 = T1.ID1
AND T1_.ID1 = T1.ID2
)