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

前端 未结 3 1788
难免孤独
难免孤独 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:14

        SELECT *
          FROM cases c
    INNER JOIN notes n ON n.case_id = c.id
                      AND n.id = (SELECT MAX(id)
                                    FROM notes
                                   WHERE case_id = c.id)
    

    Also it is a common practice to keep the pointer to the last note id directly in cases table and support it with trigger

提交回复
热议问题