关键点:
细节详见【官方题解】
select distinct A.product_id, IFNULL(B.new_price, 10) as price
from Products A
left join (
select product_id, new_price
from Products
where (product_id, change_date) in (
select product_id, max(change_date)
from Products
where change_date <= '2019-08-16'
group by product_id
)
) B
on A.product_id = B.product_id
记录自己写的错误点
-- select product_id, new_price, max(change_date)
-- from Products
-- where change_date <= '2019-08-16'
-- group by product_id
-- '''
-- | product_id | new_price | max(change_date) |
-- | ---------- | --------- | ---------------- |
-- | 1 | 20 | 2019-08-16 |
-- | 2 | 50 | 2019-08-14 |
-- '''
-- ERROR: 其中new_price为20 错误,是因为主键是 product_id 和 change_date,而不是主键是product_id;
-- 所以要通过(product_id, change_date) 定位到对应的new_price, 再加一层嵌套。