I have two tables – jobs, and jobEntries
jobEntries has a jobId that maps to jobs, but wasn’t set up as an "official" foreign key relationship so I can’t use CASCADE DELETE.
For each job, there are many jobEntries.
I want to delete from jobEntries so there is at most one jobEntry for each job, leaving only the most recent jobEntry (ORDER BY createdAt DESC)
I’ve tried many iterations of nested queries, COUNT(), HAVING, etc. but to no avail.
2
Answers
Well, just FYI I think you couldn’t use CASCADE DELETE because 1) you aren’t deleting jobs, only JobEntries and 2) You aren’t deleting all the JobEntries, only the ones that aren’t most recent.
I would encourage you to post your attempts (with Count, Having, etc.) as it would be more instructive for you to learn what mistake you made … However, be that as it may, here’s some solutions. They are written in
SQL Server
syntax, but should be applicable toMySql
with some appropriate fixes to the sql syntax.Some sample data
Approach 1, with a correlated subquery
Approach 2, with a CTE
We can ignore the
Jobs
table, since we’re only concerned with data in thejobEntries
table. Thus themany-to-many
aspect is not relevant.We need to know what the most recent job entry for each job is, which we can get with a query like this:
However, this is not enough. We need to select all the rows where the
createdAt
is not the most recent.We can do this by joining the
jobEntries
table to the output of the query above, and then deleting all the rows where thecreatedAt
column is not themaxCreatedAt
value for that jobID:DBFiddle