Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete with select in mysql

Tags:

sql

mysql

I have 3 columns(id,parent,value) with some data and this query:

SELECT * FROM test WHERE id = (
    SELECT parent FROM test WHERE id=2 AND value='value' LIMIT 1
);

The query above works great.

Now how can I delete instead of select that id in one query?

like image 411
Alqin Avatar asked Jun 09 '11 18:06

Alqin


2 Answers

You cannot delete from a table and select from that same table in a subselect.

You can however use that table in a self-join.

DELETE t1 FROM test t1
INNER JOIN test t2 ON (t1.id = t2.parent)
WHERE t2.id = 2 and t2.value = 'value'

You cannot use limit not order by in a joined delete statement.
It's either the join or the limit/order by, take your pick.

See: http://dev.mysql.com/doc/refman/5.5/en/delete.html

like image 75
Johan Avatar answered Oct 22 '22 20:10

Johan


DELETE FROM test WHERE id = ( select * from (
    SELECT parent FROM test WHERE id=2 AND value='value' LIMIT 1 ) as t
)
like image 40
Nicola Cossu Avatar answered Oct 22 '22 20:10

Nicola Cossu