2017-04-08 38 views
-1

下面是表模式如何从数据透视表拿到最后更新的价格在MYSQL

客户

------------------------------ 
id name 
------------------------------ 
1 joe 
4 jane 

产品

------------------------------ 
id title 
------------------------------ 
1 iphone 
2 ipad 

customers_products

------------------------------ 
id product_id customer_id 
------------------------------ 
1 1  1 
2 2  1 
3 1  5 
4 1  9 

价格

------------------------------------------- 
id product_id price created_at 
------------------------------------------- 
3 1  300   2017-04-01 
4 2  450   2017-04-01 
5 2  500   2017-04-02 
6 1  320   2017-04-04 
7 1  200   2017-04-05 

我想要得到的是通过用户ID分类每个产品的最后价格的这一结果,像这样

user_id product_id  last_price 
1  1    200    

这是1号(price_history行没有产品的最新更新价格7)

这是我到目前为止已经完成,它给了不正确的结果

select 
id,prices.price as current_price,customers_products as price 
from prices 
join products on products.id = prices.product_id 
join customers_products on customers_products.product_id = prices.product_id 
where customers_products.customer_id = 1 
group by prices.product_id order by prices.id desc 

真正会感谢你的帮助!

谢谢!

+0

什么是你查询的输出,而究竟什么是错的输出元组? –

回答

1

你可以使用在为得到最大的价格加入到你的customers_products

select customers_products.customer_id , customers_products.product_id, prices.price as last_price 
from customers_products 
inner join prices on prices.product_id = customers_products 
where (created_at ,product_id) in (
    select max(created_at), product_id 
    from price 
    group product_id 
)