Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn this MySQL SELECT query into a DELETE query?

I want to delete certain items from the database. I have the following query:

SELECT * 
FROM sheets, entries 
WHERE entries.sheetID = sheets.id AND sheets.clientID = 13

This works, and returns 2 results.

Now I want to turn this SELECT query into a DELETE query. However, the following doesn't work:

DELETE FROM sheets, entries 
WHERE entries.sheetID = sheets.id AND sheets.clientID = 13

MySQL throws the following error:

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 'WHERE entries.sheetID = sheets.id AND sheets.clientID = 13' at line 1

What am I doing wrong here?

like image 320
Mathias Bynens Avatar asked Dec 09 '22 18:12

Mathias Bynens


1 Answers

MySQL 4 and up supports deleting from multiple tables at once, using the following syntax:

DELETE sheets, entries
FROM sheets, entries 
WHERE entries.sheetID = sheets.id AND sheets.clientID = 13

If you're using MySQL below version 4, then you need to delete rows from one table at a time, and you can use one of the other solutions posted here.

like image 114
Andre Miller Avatar answered Dec 15 '22 00:12

Andre Miller