Piero
Piero

Reputation: 3

Select max value from different tables in mysql

I want to select the most expensive product each customer bought, but I have the information in 3 tables: Customers, Purchases, ProductsPrices.

Tables look like:

Customers:

Customer_ID | Customer_Name

Purchases:

Customer_ID | Product_ID

ProductPrices:

Product_ID | Price

What i'm running is:

SELECT  
Customer_Name, max(Price), Purchases.Product_ID
            FROM Customers 
            LEFT JOIN Purchases 
            ON Customers.Customer_ID=Purchases.Customer_ID
            LEFT JOIN ProductPrices
            ON Purchases.Product_ID=ProductPrices.Product_ID
                        GROUP BY Customer_Name
                        ORDER BY ABS(Price) DESC
                        ;

And the output i'm getting is the names and the highest purchase correct, but the product_id is the first, and not associated with the highest price.

Can you help me to spot what am I doing wrong?

EDIT:

To make it easier for you, I created this:

http://sqlfiddle.com/#!2/db7f9/1

Upvotes: 0

Views: 2641

Answers (2)

echo_Me
echo_Me

Reputation: 37233

try this

    SELECT Customer_Name, max(Price) price , Product_ID FROM (
 SELECT  
Customer_Name, Price, Purchases.Product_ID
        FROM Customers 
        INNER JOIN Purchases 
        ON Customers.Customer_ID=Purchases.Customer_ID
        INNER JOIN ProductPrices
        ON Purchases.Product_ID=ProductPrices.Product_ID


                    ORDER BY ABS(Price) DESC
)t

GROUP BY Customer_Name

DEMO HERE

OUTPUT:

  CUSTOMER_NAME     PRICE   PRODUCT_ID
     John           30000   3
     Kate           30000   3
     Peter          20000   2

Upvotes: -1

geomagas
geomagas

Reputation: 3280

Try this:

select distinct c.Customer_Name,pp.Product_Id,m.Price
from 
  (select Customer_ID,max(Price) as Price
  from Purchases p join ProductPrices pp on (p.Product_ID=pp.Product_ID)
  group by Customer_ID) m
join Customers c on (m.Customer_ID=c.Customer_ID)
join ProductPrices pp on (pp.Price=m.Price)
join Purchases p on (m.Customer_ID=p.Customer_ID and p.Product_ID=pp.Product_ID)

Note: If a customer purchased multiple products with the same price, this will give you muliple rows per Customer.

Upvotes: 2

Related Questions