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

前端 未结 10 1755
深忆病人
深忆病人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:21

    Another approach would be to use a NOT EXISTS condition in your join condition to test for later purchases:

    SELECT *
    FROM customer c
    LEFT JOIN purchase p ON (
           c.id = p.customer_id
       AND NOT EXISTS (
         SELECT 1 FROM purchase p1
         WHERE p1.customer_id = c.id
         AND p1.id > p.id
       )
    )
    

提交回复
热议问题