从mysql中的不同表中选择最大值

时间:2013-10-12 10:59:46

标签: mysql sql

我想选择每个客户购买的最昂贵的产品,但我有3个表中的信息:客户,购买,产品价格。

表格如下:

客户:

Customer_ID | Customer_Name

购买:

Customer_ID | Product_ID

ProductPrices:

Product_ID | Price

我正在运行的是:

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
                        ;

我得到的输出是名称和最高购买正确,但product_id是第一个,与最高价格无关。

你能帮助我发现我做错了吗?

编辑:

为了让您更轻松,我创建了这个:

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

2 个答案:

答案 0 :(得分:1)

试试这个:

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)

注意:如果客户购买了多个价格相同的产品,这将为每位客户提供多个行。

答案 1 :(得分:-2)

试试这个

    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

输出:

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