以下是表架构
客户
------------------------------
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 row no 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
)