select i.description, p.cost, i.itemid,p.dateq as datessss
from item i, (select itemid,max(date) as dateq,cost
from price group by itemid) p
WHERE i.itemid = p.itemid
description cost itemid datessss
ChickenRatePerKG 108 26 2015-03-02
LiveBird 55.25 27 2015-03-02
Eggs 197 28 2015-03-02
这是我的价格表
itemid date cost
28 2015-03-02 450
28 2015-02-14 380
28 2015-02-13 200
28 2015-02-01 400
28 2014-01-23 197
28 2014-01-22 197
它获取的是正确的日期,但不是与该日期对应的价格。
有人可以帮我找到问题吗?
最佳答案
您可以通过不同的方式来完成此操作,使用左连接
或使用不存在
或相关子查询
select
i.description,
i.itemid,
p.cost,
p.date as datessss
from item i
join price p on p.itemid = i.itemid
left join price p1 on p1.itemid = p.itemid and p1.date > p.date
where p1.itemid is null ;
或者
select
i.description,
i.itemid,
p.cost,
p.date as datessss
from item i
join price p on p.itemid = i.itemid
where not exists
(
select 1 from price p1
where p1.itemid = p.itemid and p1.date > p.date
)
<强> DEMO
关于mysql - mysql中max函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28806936/