8

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?

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

6 Comments

What if the child gets deleted first?
@Justin, this will only delete items in t1. MySQL will use a temporary table if needed to hold the values in the joined resultset.
I don't get it. From where did you get t1 and t2? I have one table test.
@Alqin, he instantiated t1 and t2 to differentiate between the table from which he is deleting and the table to which he is joining.
@Johan please take a second look at syntax. I does not work with LIMIT 1 at the end.
|
5
DELETE FROM test WHERE id = ( select * from (
    SELECT parent FROM test WHERE id=2 AND value='value' LIMIT 1 ) as t
)

4 Comments

This actually works! My first impression was that won't work but it does. Tanks!
@Nick, Yes I have and besides, the text in the comment is a literal quote from the link provided.
Wow, are there badges for having a downvoted answer accepted? So, I don't understand: was the table cached because it was given an alias?
@Justin, nick is tricking the query optimizer. It doesn't know it selecting from and deleting from the same table. Because he's nesting the table 2 levels deep. The query optimizer doesn't test for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.