我最近在运行delete语句时发生了一个事件,它删除了所有记录。我发现了错误,但不明白为什么它可以执行。我可以简单地演示这个事件:
create table A(
aid int,
description varchar(50)
);
create table B(
bid int,
description varchar(50)
);
insert into A values(1, 'Row 1');
insert into A values(2, 'Row 2');
insert into A values(3, 'Row 3');
insert into B values(22, 'Row 1');
insert into B values(23, 'Row 2');
insert into B values(24, 'Row 3');
delete from A where aid in (select aid from B);
delete语句删除了整个表A记录,甚至列aid表B不存在. 为什么子查询失败而语句没有失败?我在PostgreSql和Oracle上运行它,结果都是一样的。
由于表B没有辅助列
delete from A where aid in (select aid from B);
被计算为
delete from A where aid in (select A.aid from B);
但是你想
delete from A where A.aid in (select B.bid from B);
限定所有列是良好的编程实践,至少在涉及多个表时是这样。