2014-04-30 17 views
0

我想知道爲什麼我的刪除不起作用。當只有1行被允許時,刪除最後插入的行SQL

我試圖刪除SQL行,插入時最後一個SQL行,當只有一行的IP地址和用戶ID被接受,只有一行的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行不刪除?

+0

你能不能簡單地做'刪除訪問者WHERE ip_address ='「。$ ipAddress。''AND user_id =''ORDER BY user_id DESC LIMIT 1' –

+0

@ Fred-ii-我認爲你的意思是'AND user_id <>''' – Digzol

+0

@Digzol我會說我站*糾正* ;-) –

回答

2

簡單:因爲不允許使用子查詢中要刪除的表。只是separatly運行SELECT查詢,並將結果進行刪除...

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...)))。但這種方式在各方面都很糟糕

+0

所以只是'刪除訪問者WHERE ip_address LIMIT 1'? – user3561965

+0

@ user3561965:NO。首先執行子查詢,獲取結果(即一行),然後_then_使用從SELECT獲得的數據執行刪除操作。只需要2個查詢,而不是試圖將它全部整合在一起。 PS:你可能會因爲注入新代碼而容易受到攻擊 –