SQL 在 LEFT JOIN 中获取最大日期时间

SQL get MAX datetime in LEFT JOIN

我是 运行 针对 table 的查询并进行左连接以尝试从左侧 table 获取最近日期的记录,但它没有被提取与日期时间列相关的其他值(用户和注释)

SELECT
    i.customer_sequence,
    i.due_date,
    
    MAX(cn.datetime) as notes_datetime,
    cn.user as notes_user,
    cn.notes as notes_notes
FROM
    billing_invoices i
LEFT JOIN customer_notes cn
    ON i.customer_sequence = cn.customer_seq
WHERE
    cn.type = 'Accounts' AND
    i.customer_sequence <> '0' AND
    i.status = 'Unpaid' AND
    i.directdebit <> 'Y'
GROUP BY
    i.customer_sequence
ORDER BY
    i.due_date DESC

聚合不是这里的解决方案。您想要连接的 table 中的整行,因此这建议改为过滤。如果你是运行MySQL8.0,我推荐window函数:

SELECT *
FROM (
    SELECT
        i.customer_sequence,
        i.due_date,
        ROW_NUMBER() OVER(PARTITION BY i.customer_sequence ORDER BY cn.datetime DESC) rn,
        cn.datetime as notes_datetime,
        cn.user as notes_user,
        cn.notes as notes_notes
    FROM billing_invoices i
    LEFT JOIN customer_notes cn
        ON  i.customer_sequence = cn.customer_seq
        AND cn.type = 'Accounts'
    WHERE
        i.customer_sequence <> '0' AND
        i.status = 'Unpaid' AND
        i.directdebit <> 'Y'
) t
ORDER BY i.due_date DESC    

请注意,我将 left joined table 上的条件从 WHERE 子句移动到联接的 ON 子句(否则,这就像一个inner join).


在早期版本中,一个选项是相关子查询:

SELECT
    i.customer_sequence,
    i.due_date,
    cn.datetime as notes_datetime,
    cn.user as notes_user,
    cn.notes as notes_notes
FROM billing_invoices i
LEFT JOIN customer_notes cn
    ON  i.customer_sequence = cn.customer_seq
    AND cn.type = 'Accounts'
    AND cn.datetime = (
        SELECT MAX(cn1.datetime)
        FROM customer_notes cn1
        WHERE i.customer_sequence = cn1.customer_seq AND cn1.type = 'Accounts'
    )
WHERE
    i.customer_sequence <> '0' AND
    i.status = 'Unpaid' AND
    i.directdebit <> 'Y'