Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a "distinct" join with MySQL

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

Product table:

Id = int Name = varchar Manufacturer = varchar UPC = varchar Date_added = datetime 

Price_h table:

Id = int Product_id = int Price = int Date = datetime 

I can perform a simple LEFT JOIN:

SELECT Product.UPC, Product.Name, Price_h.Price, Price_h.Date FROM Product LEFT JOIN Price_h ON Product.Id = Price_h.Product_id; 

But as expected if I have more than one entry for a product in the price history table, I get one result for each historical price.

How can a structure a join that will only return one instance of each produce with only the newest entry from the price history table joined to it?

like image 705
Steven Potter Avatar asked Jun 21 '10 21:06

Steven Potter


People also ask

How use distinct inner join in MySQL?

Here is the query: $sql = mysql_query("SELECT DISTINCT TA_user FROM table_A INNER JOIN table_B ON table_B.id = table_A.

How do you select distinct columns in join queries?

DISTINCT is for all the columns in the select clause, which means all columns combined will be used to get distinct rows. TOP X will only select the number of rows mentioned in X .

How can I get distinct values from two tables in MySQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.


2 Answers

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 
like image 110
OMG Ponies Avatar answered Oct 02 '22 20:10

OMG Ponies


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)); 
like image 32
a1ex07 Avatar answered Oct 02 '22 20:10

a1ex07