How do I delete mysql records from 2 tables, but if no records in 2nd table still delete from 1st table?

StackOverflow https://stackoverflow.com/questions/21711726

  •  10-10-2022
  •  | 
  •  

Question

This works when a job has files. It deletes the file records from files table and job records from jobs table, however, if job has no files, nothing happens. I want it to still delete the job record from the jobs table if the job doesn't have files associated with it.

DELETE jobs, files FROM jobs INNER JOIN files WHERE jobs.id = $id AND files.jobid = jobs.id

I tried like the following but it didn't work:

DELETE jobs, files FROM jobs INNER JOIN files WHERE jobs.id = $id OR files.jobid = jobs.id

Also tried this, but it didn't work:

DELETE jobs, files FROM jobs INNER JOIN files on jobs.id = files.jobid WHERE jobs.id = $id

EDIT:

here is what worked. it's based from the answer marked as correct below, but slightly different.

DELETE jobs, files FROM jobs LEFT JOIN files ON files.jobid = jobs.id WHERE jobs.id = $id

it didn't like that short code or whatever that is (when people say files f or jobs j then later they say f.jobid or j.id). and it may not have liked the stars/asterisks when first declaring the tables (not sure).

Was it helpful?

Solution

Just using a LEFT JOIN would solve your problem:

DELETE j.*, f.*
FROM jobs j
LEFT JOIN files f
    ON f.jobid = j.id
WHERE j.id = $id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top