MYSQL - Join most recent matching record from one table to another

前端 未结 3 1786
难免孤独
难免孤独 2020-12-10 09:44

I have two tables that look like this:

Table: cases

id
name
status
case_no

Table: notes

id
case_id
note_date
notes

3条回答
  •  抹茶落季
    2020-12-10 10:11

    I have been having same problem recently and this forum has helped me a lot but I found the OMG Ponies answer isn't complete. It works for those cases with notes but it doesn't for cases without notes which is my issue. My answer is similar but instead joining the group query with notes, I join it with cases.

    It would be:

    SELECT c.*, x.*
    FROM CASES c
        LEFT JOIN (SELECT n.case_id, MAX(n.note_date) AS max_note_date
                   FROM NOTES n
                   GROUP BY n.case_id) y ON y.case_id = c.case_id
        LEFT JOIN NOTES x ON x.case_id = c.case_id AND x.note_date=y.max_note_date
    

    It's also valid to get just cases with notes removing one left keyword or both

提交回复
热议问题