mysql中的max函数问题

时间:2015-03-02 10:00:09

标签: mysql

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

获取正确的日期,但不是与日期对应的价格。

有人可以帮我找到问题吗?

2 个答案:

答案 0 :(得分:0)

未经测试,但这应该可以解决问题:

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 having date=max(date)) p
WHERE i.itemid = p.itemid 

如果没有having,你就不知道你会得到哪一行。

答案 1 :(得分:0)

您可以使用left join或使用not existscorrelated sub query

以不同方式执行此操作
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 ;

OR

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