3

Why is this query deleting all users when the user_id column does not exist at the profile table?

The initial query:

DELETE FROM users
    WHERE user_id IN (
        SELECT user_id FROM profile
        )
    AND user_id != 35
    AND user_id != 6; 

To be more specific.

The IN statement query returns:

SELECT user_id FROM profile;

ERROR:  column "user_id" does not exist
LINE 1: SELECT user_id FROM profile;

Running the initial query returns

DELETE 100

Why is that happening?

Shouldn't it have stopped the execution upon error or return false or null?

Running PostgreSQL Server 9.0

4

1 回答 1

8

根据 ANSI 标准,此行为是正确的。

如果未限定的列名未在内部范围内解析,则将考虑外部范围。因此,您正在执行一个无意的相关子查询。

只要表格profile包含至少一行,那么

 FROM users
 WHERE user_id IN (
        SELECT user_id FROM profile
        )

最终将匹配所有行users(除了任何不评估为真的地方)users.user_id IS NULLWHERE NULL IN (NULL)为了避免这个可能的问题,您可以使用两个部分名称。

DELETE FROM users
WHERE  user_id IN (SELECT p.user_id
                   FROM   profile p) 

会给出错误

p.user_id 列不存在:

于 2013-05-06T19:59:57.000 回答