Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting rows from multiple tables in MySQL

Tags:

sql

mysql

I am trying to delete a project from the projects table and all the images associated with that project in the images table.

Lets say p_id = 10

DELETE FROM projects, images WHERE projects.p_id = ? AND images.p_id = ?

What is wrong with this query?

like image 656
Ross Avatar asked Dec 09 '22 16:12

Ross


2 Answers

DELETE projects, images 
FROM projects, images 
WHERE projects.p_id = ? 
AND projects.p_id = images.p_id;
like image 169
Brant Messenger Avatar answered Dec 12 '22 05:12

Brant Messenger


As Chacha102 noted, the problem of your query was the AND in the WHERE clause.

However, you may want to use the JOIN syntax for multi-table DELETEs, which I find easier to read:

DELETE     projects, images
FROM       projects 
LEFT JOIN  images ON images.p_id = projects.p_id
WHERE      projects.p_id = 10;
like image 22
Daniel Vassallo Avatar answered Dec 12 '22 07:12

Daniel Vassallo