简体   繁体   中英

Deleting record with lowest ID

When I type this query in MySQL :

DELETE FROM myTable WHERE ID = ( SELECT Min( ID ) FROM myTable )

I get the following error message :

#1093 - You can't specify target table 'myTable' for update in FROM clause

What is the problem ?

What is the right equivalent ?

Basically in MySQL you can't do an update on a table which you use in the SELECT part. For detail you could check this behaviour which is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html

In theory every DELETE is an UPDATE so that's why you get this error.

You could simply do following:

DELETE FROM myTable 
ORDER BY my_id
LIMIT 1;

尝试

DELETE FROM myTable ORDER BY ID LIMIT 1;

That's because in MySQL, you can't modify the same table which you use in the SELECT part.

Read: http://dev.mysql.com/doc/refman/5.6/en/update.html

In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html

Instead of nested subquery, execute the operation in two parts, or alternatively use a simple where clause.

Try :

$min_id = SELECT Min( ID ) FROM myTable
DELETE FROM myTable WHERE ID = $min_id

Now you shall not get any error.

Cheers..!

尝试这个

DELETE FROM `table_name` ORDER BY id LIMIT 1;
DELETE FROM myTable WHERE ID = (SELECT ID FROM myTable ORDER BY ID LIMIT 1)
DELETE FROM myTable ORDER BY ID ASC LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM