2012-03-28 132 views
0

我使用的是MySQL 5.0.77數據庫使用查詢:如何使用子查詢中刪除/更新查詢在MySQL

Delete from IPADDRESS 
where visitdate Not in (SELECT max(visitdate) FROM IPADDRESS WHERE USERNAME='MGSH0002') 
and USERNAME='MGSH0002' 

執行時,我收到此錯誤:

你可以從子句中指定目標表IPADDRESS用於更新

+0

爲什麼這是用java標籤?移動到mysql – Jayan 2012-03-28 12:30:11

回答

3

當然不是最好的解決辦法,但對於你的問題,這將這樣的伎倆:

delete i1 from 
    IPADDRESS i1, 
    IPADDRESS i2 
where 
    i1.username = i2.username 
    and i1.username = 'MGSH0002' 
    and i1.visitdate < i2.visitdate 

的替代性和更聰明的解決方案是下面的語句:

delete i1 from 
    IPADDRESS i1, 
    (select max(visitdate) visitdate from IPADDRESS where username = 'MGSH0002') temp 
where 
    i1.username = 'MGSH0002' 
    and i1.visitdate < temp.visitdate 
+0

thnks這是工作我有一個更多的查詢「刪除從IPADDRESS where visitdate不在(SELECT visitdate FROM(SELECT visitdate FROM IPADDRESS WHERE USERNAME ='MGSH0002 'ORDER BY visitdate DESC)其中ROWNUM <4)和USERNAME ='MGSH0002'「它在oracle中工作,但不在mysql plz幫助 – manorma 2012-03-28 13:01:00

+1

第二種解決方案當然要聰明得多。它可能需要'group by username'成爲'temp'子查詢中的WHERE username ='MGSH0002'',但它比第一個好。並且如果有'(用戶名,訪問日期)的索引,則速度更快' – 2012-03-29 06:45:02

+0

Thx ypercube!我想編輯我的第二個解決方案,現在我們有了一個聰明的解決方案。 – GreenTurtle 2012-03-29 11:31:46