我在检索具有重复ID的最新记录时遇到问题。
产品表
product id prodoctcode
1 po1
2 po2
3 po3
4 po4
5 po5
6 po6
7 po7
价格表
priceid product id price yearadded
1 1 10 2018
2 1 13 2019
3 2 14 2015
4 2 15 2016
5 3 16 2019
6 4 17 2017
7 4 18 2015
我想要只检索最新记录的结果。
product id prodoctcode price yearadded
1 po1 13 2019
2 po2 15 2016
3 po3 16 2019
4 po4 17 2017
我尝试选择distinct(product id)
,但没有运气
答案 0 :(得分:0)
您还需要与子查询联接以获取最大年份
select
a.`product id`, a.prodoctcode, b.price, b.yearadded
from
producttable a
inner join
pricetable b on a.`product id` = b.`product id`
inner join
(select `product id`, max(yearadded) year
from pricetable
group by `product id`) on t.`product id` = b.`product id` and t.year = b.yearadded