我想知道为什么我的删除无效。
我正在尝试删除SQL行,当只接受带有IP地址和用户ID的1行时,最后插入的SQL行只接受一行带有IP地址和空白用户ID的行。
这是我的代码:
DELETE
FROM visitor
WHERE ip_address NOT IN
(SELECT ip_address
FROM visitor
WHERE ip_address = '".$ipAddress."'
AND user_id = ''
ORDER BY user_id DESC LIMIT 1)
为什么我的SQL行没有DELETING?
答案 0 :(得分:2)
简单:因为不允许在子查询中使用要删除的表。只需分别运行SELECT
查询,然后使用结果执行DELETE ...
RTM,它明确指出这里不允许这样做:
Incorrectly used table in subquery: Error 1093 (ER_UPDATE_TABLE_USED) SQLSTATE = HY000 Message = "You can't specify target table 'x' for update in FROM clause" This error occurs in cases such as the following, which attempts to modify a table and select from the same table in the subquery: UPDATE t1 SET column2 = (SELECT MAX(column1) FROM t1); You can use a subquery for assignment within an UPDATE statement because subqueries are legal in UPDATE and DELETE statements as well as in SELECT statements. However, you cannot use the same table (in this case, table t1) for both the subquery FROM clause and the update target.
特别是最后一句很重要: 但是,对于子查询FROM子句和更新目标,您不能使用相同的表(在本例中为表t1)。
这有一种愚蠢的方式,它很愚蠢,但上次检查时它起作用,即将你的子查询包装在另一个子(WHERE x IN (SELECT id FROM (SELECT id FROM tbl...))
)中。但这在各方面都很糟糕