MySQL groupwise MAX() returns unexpected results

前端 未结 3 618
青春惊慌失措
青春惊慌失措 2020-12-02 00:35

TABLE: LOAN

Loan_no     Amount        SSS_no              Loan_date

7           700.00        0104849222          2010-01-03 
8                    


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 01:37

    The MySQL reference suggests several ways to solve this. The simplest is a subquery:

    SELECT *
    FROM   loan l1
    WHERE  loan_date=(SELECT MAX(l2.loan_date)
                  FROM loan l2
                  WHERE l1.sss_no = l2.sss_no);
    

    Given that this type of subqueries potentially have bad performance, they also suggest using a JOIN (essentially Mahmoud Gamal's answer):

    SELECT l1.loan_no, l1.amount, l1.sss_no, l1.loan_date
    FROM loan l1
    JOIN (
      SELECT loan_no, MAX(loan_date) AS loan_date
      FROM loan
      GROUP BY sss_no) AS l2
      ON l1.loan_date = l2.loan_date AND l1.sss_no = l2.sss_no;
    

    A third option is:

    SELECT l1.loan_no, l1.amount, l1.sss_no, l1.loan_date
    FROM loan l1
    LEFT JOIN loan l2 ON l1.sss_no = l2.sss_no AND l1.loan_date < l2.loan_date
    WHERE l2.sss_no IS NULL;
    

    The LEFT JOIN works on the basis that when l1.loan_date is at its maximum value, there is later l2.loan_date, so the l2 row values will be NULL.

    All these should have the same output, but likely differ in performance.

提交回复
热议问题