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

前端 未结 10 1756
深忆病人
深忆病人 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

    I found this thread as a solution to my problem.

    But when I tried them the performance was low. Bellow is my suggestion for better performance.

    With MaxDates as (
    SELECT  customer_id,
                    MAX(date) MaxDate
            FROM    purchase
            GROUP BY customer_id
    )
    
    SELECT  c.*, M.*
    FROM    customer c INNER JOIN
            MaxDates as M ON c.id = M.customer_id 
    

    Hope this will be helpful.

提交回复
热议问题