[英]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. 我想选择每个客户购买的最昂贵的产品,但是我在3个表中提供了信息:客户,购买,产品价格。
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. 我得到的输出是名称和最高购买正确率,但是product_id是第一个,并且与最高价格无关。
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 http://sqlfiddle.com/#!2/db7f9/1
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. 注意:如果客户以相同的价格购买了多个产品,则每个客户可以看到多行。
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
OUTPUT: 输出:
CUSTOMER_NAME PRICE PRODUCT_ID
John 30000 3
Kate 30000 3
Peter 20000 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.