Home > Software engineering >  MySQL limiting within a LEFT JOIN
MySQL limiting within a LEFT JOIN

Time:10-22

Hi so i have a database with the multiple tables with different records like so,

- table_1
    - student_name
    - student_id
    - id
    - note
    - ...

- table_2
    - id
    - leave
    - ...

leave currently contains the records of all the days the student has taken day off.

sample data for table_2 as requested

id leave ...
675 2011-05-04 ...
675 2012-04-15 ...
675 2021-06-23 ...
345 2019-10-14 ...
345 2011-04-05 ...
345 2019-02-13 ...

So my question is how do i LEFT JOIN the tables and return the last leave date for the student instead of fetching all the leave date's for that particular student.

here's the current output that i'm getting

name id note last absent ...
John Doe 675 good student 2011-05-04 ...
John Doe 675 good student 2012-04-15 ...
John Doe 675 good student 2021-06-23 ...
Jack Sparrow 345 average student 2019-10-14 ...
Jack Sparrow 345 average student 2019-10-14 ...
Jack Sparrow 345 average student 2019-02-13 ...
Ryan Reynolds 567 below average student 2011-07-22 ...

Here is my expected output.

name id note last absent ...
John Doe 675 good student 2021-06-23 ...
Jack Sparrow 345 average student 2019-10-14 ...
Ryan Reynolds 567 below average student 2011-07-22 ...

All help is appreciated and thanks in advance.

CodePudding user response:

As Martin already commented, you need to use an aggregate query. Since dates are effectively ordered lexicographically, the most recent date in a set of dates is its maximum. Therefore, you need to use the MAX() aggregator. Since you want to get the most recent date per student, you need to group the query by student. And since MySQL usually does not want you to print columns that are not in the GROUP BY clause, you'll need to add all columns from TABLE_1 to that clause. This should do what you want:

SELECT TABLE_1.NAME, TABLE_1.ID, TABLE_1.NOTE, MAX(TABLE_2.LEAVEDATE) AS last_absent
FROM TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.ID = TABLE_2.ID
GROUP BY TABLE_1.ID, TABLE_1.NAME, TABLE_1.NOTE;
  • Related