2

How to delete rows using delete and select mysql

I use this rows not work :

delete from items T1 where T1.base_item = 
(SELECT T2.type,T2.id From furniture T2 where T2.type = 'i' );
2
  • What error do you get from de database? Commented Oct 7, 2013 at 19:22
  • #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'T1 where T1.base_item = (SELECT T2.type,T2.id From furniture T2 where T2.type = ' at line 1 Commented Oct 7, 2013 at 19:24

3 Answers 3

3

This does not work because = expects a single value while the subselect returns a result set.

There are two approaches you can take, you can use an IN() clause or your can delete across a join.

The first would look like this:

DELETE FROM items
WHERE base_item IN (SELECT id FROM furniture WHERE type = 'i')

Note that only a single field should be specified in the subselect. I am assuming that furniture.id relates to items.base_item in this case. If furniture.type is really the matching field, use that in the subselect instead.

The second approach would look like this:

DELETE items
FROM items INNER JOIN furniture
  ON items.base_item = furniture.id
WHERE furniture.type = 'i'

Again my assumption here is that items.base_item relates to furniture.id.

Which is better to use (assuming all applicable fields are indexed) would likely depend on the number of rows expected in each table and the cardinality of your data. You might want to test yourself to see which is more efficient for your use case.

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

Comments

2

Your SELECT statement is returning a set (or records) with two columns. You need to use IN (not =) and only SELECT a single column

delete from items T1 where T1.base_item in (
   SELECT T2.id From furniture T2 where T2.type = 'i' 
); 

Comments

1

Is this what you are trying to do? You can use a join to delete the items you want

DELETE T1
FROM items T1 
INNER JOIN furniture T2 ON T1.base_item = T2.id
WHERE T2.type = 'i'

Comments

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.