MySQL: Can I do a left join and pull only one row from the join table?

Let me sum up what I understood: you’d like to select each ticket and its last solution.

I like using the following pattern for this kind of question as it avoids the subquery pattern and is therefore rather good where performance is needed. The drawback is that it is a bit tricky to understand:

SELECT
  t.*,
  s1.*
FROM tickets t
INNER JOIN solutions s1 ON t.id = s1.ticket_id
LEFT JOIN solutions s2 ON s1.ticket_id = s2.ticket_id AND s2.id > s1.id
WHERE s2.id IS NULL;

I wrote only the heart of the pattern for a better understanding.

The keys are:

  • the LEFT JOIN of the solutions table with itself with the s1.ticket_id = s2.ticket_id condition: it emulates the GROUP BY ticket_id.

  • the condition s2.id > s1.id : it is the SQL for “I only want the last solution”, it emulates the MAX(). I assumed that in your model, the last means with the greatest id but you could use here a condition on the date. Note that s2.id < s1.id would give you the first solution.

  • the WHERE clause s2.id IS NULL: the weirdest one but absolutely necessary… keeps only the records you want.

Have a try and let me know 🙂

Edit 1: I just realised that the second point assumption was oversimplifying the problem. That makes it even more interesting :p I’m trying to see how this pattern may work with your date, id ordering.

Edit 2: Ok, it works great with a little twist. The condition on the LEFT JOIN becomes:

LEFT JOIN solutions s2 ON s1.ticket_id = s2.ticket_id
  AND (s2.date > s1.date OR (s2.date = s1.date AND s2.id > s1.id))

Leave a Comment