2017-04-08 9 views
-1
でピボットテーブルから最後に更新価格を取得する方法

は、ここでテーブルスキーマにはMYSQL

------------------------------ 
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 name 
------------------------------ 
1 joe 
4 jane 

製品

顧客であります

------------------------------------------- 
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 

は私が取得しようとしていることは、製品の最終更新価格なし1(price_history行なしでこの

user_id product_id  last_price 
1  1    200    

のように、ユーザIDごとに分類、各製品の最終価格のこの結果であり、 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 
)