How to make a “distinct” join with MySQL

前端 未结 5 1017
悲&欢浪女
悲&欢浪女 2021-02-05 04:14

I have two MySQL tables (product and price history) that I would like to join:

Product table:

Id = int
Name = varchar
Manufacturer = varchar         


        
5条回答
  •  清酒与你
    2021-02-05 04:48

    Use:

       SELECT p.upc,
              p.name,
              ph.price,
              ph.date
         FROM PRODUCT p
    LEFT JOIN PRICE_H ph ON ph.product_id = p.id
         JOIN (SELECT a.product_id, 
                      MAX(a.date) AS max_date
                 FROM PRICE_H a
             GROUP BY a.product_id) x ON x.product_id = ph.product_id
                                     AND x.max_date = ph.date
    

提交回复
热议问题