SQL join: selecting the last records in a one-to-many relationship

前端 未结 10 1678
深忆病人
深忆病人 2020-11-22 08:48

Suppose I have a table of customers and a table of purchases. Each purchase belongs to one customer. I want to get a list of all customers along with their last purchase in

10条回答
  •  心在旅途
    2020-11-22 09:27

    Tested on SQLite:

    SELECT c.*, p.*, max(p.date)
    FROM customer c
    LEFT OUTER JOIN purchase p
    ON c.id = p.customer_id
    GROUP BY c.id
    

    The max() aggregate function will make sure that the latest purchase is selected from each group (but assumes that the date column is in a format whereby max() gives the latest - which is normally the case). If you want to handle purchases with the same date then you can use max(p.date, p.id).

    In terms of indexes, I would use an index on purchase with (customer_id, date, [any other purchase columns you want to return in your select]).

    The LEFT OUTER JOIN (as opposed to INNER JOIN) will make sure that customers that have never made a purchase are also included.

提交回复
热议问题