mysql delete的一個問題

mysql> select * from a;
+------+-------+
| id   | name  |
+------+-------+
|    1 | test1 |
|    2 | test2 |
|    3 | test3 |
|    4 | test3 |
|    5 | test3 |
+------+-------+
5 rows in set (0.00 sec) 

對這樣的一個表,需要刪除 name相同的記錄。id沒有要求,但我這裏只留下最小的id。

mysql> delete from a where id not in (select min(id) as id from a group by name);
ERROR 1093 (HY000): You can't specify target table 'a' for update in FROM clause

google查詢結構,原來mysql不支持這樣的同時有select跟delete/update同一個表的操作。不過可以變通一下:

mysql> delete from a where id not in (select * from (select min(id) as id from a group by name) b where a.id=b.id);
Query OK, 2 rows affected (0.01 sec)

 

當然這樣的問題在sqlserver上沒有了。

delete from #a where id not in (select min(id) from #aa group by name)

這樣完全沒有問題。

 

 

 

發佈了63 篇原創文章 · 獲贊 2 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章