How to make a “distinct” join with MySQL

前端 未结 5 1018
悲&欢浪女
悲&欢浪女 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
    
    0 讨论(0)
  • 2021-02-05 04:48
    SELECT Product.UPC, Product.Name, Price_h.Price, Price_h.Date
    FROM Product
    LEFT JOIN Price_h
    ON (Product.Id = Price_h.Product_id AND Price_h.Date = 
      (SELECT MAX(Date) FROM Price_h ph1 WHERE ph1.Product_id = Product.Id));
    
    0 讨论(0)
  • 2021-02-05 04:52

    Why not keep it simple and fast:

    SELECT 
     Product.UPC, Product.Name, Price_h.Price, Price_h.Date
    FROM 
     Product
    LEFT JOIN 
     Price_h
     ON Product.Id = Price_h.Product_id;
    ORDER BY
     Price_h.Date DESC
    LIMIT 1
    
    0 讨论(0)
  • 2021-02-05 04:55
    SELECT n.product_id, 
           n.product_name,
           n.product_articul,
           n.product_price,
           n.product_discount,
           n.product_description, 
           n.product_care,
           (SELECT photo_name FROM siamm_product_photos WHERE product_id = n.product_id LIMIT 1) AS photo_name
    FROM siamm_product as n;
    
    0 讨论(0)
  • 2021-02-05 05:00

    Try this:

    SELECT Product.UPC, Product.Name, Price_h.Price, MAX(Price_h.Date)
     FROM Product
     INNER JOIN Price_h
       ON Product.Id = Price_h.Product_id
    GROUP BY Product.UPC, Product.Name, Price_h.Price
    
    0 讨论(0)
提交回复
热议问题