在视图中获取最新的表

时间:2012-01-04 19:54:31

标签: mysql sql view

我正在尝试创建一个视图,该视图获取每个项目历史记录的最新信息并将其连续返回。我想要运行的查询如下:

SELECT item_pk.Id Id, item_name.Value Name 
FROM item_pk
JOIN 
(
    SELECT * FROM item_name
    ORDER BY Occurred DESC
) item_name ON item_name.Id = item_pk.Id
GROUP BY item_pk.Id

此查询工作正常,并返回我想要的,但当我尝试将其转换为视图时,它不会让我使用子查询。当我尝试:

CREATE VIEW item_name_latest AS SELECT * FROM item_name ORDER BY Occurred DESC;
CREATE VIEW item AS SELECT item_pk.Id Id, item_name.value Name 
FROM item_pk
JOIN item_name_latest item_name ON item_name.Id = item_pk.Id
GROUP BY item_pk.Id

item视图会产生错误的结果。我得到的结果与我直接加入item_name的结果完全相同,而没有应产生更正顺序的中间视图。也就是说,我收到的是最早的,而不是从item_name收到每个项目的最新行。直接调用SELECT语句(而不是视图)也会产生错误的结果。

说我有以下数据:

Id | Value        | Occurred
1    Bob            1325697408000
1    Bobbie         1325697536000
2    Stuff          1325697822000
2    More Stuff     1325697823000
2    Latest Stuff   1325697824000
1    Roberta        1325697945000

预期结果(以及给定查询子查询的实际结果)是:

1    Roberta
2    Latest Stuff

视图的实际结果是:

1    Bob
2    Stuff

有没有办法用视图生成预期值,还是有更好的方法来获取值?

1 个答案:

答案 0 :(得分:1)

您希望这样创建视图:

create view item_latest as
select
  id, 
    max(occurred) as latestoccurred 
from 
    item_name 
group by
    id;

create view item as
select
    i1.id,
    i1.value
from
    item_name i1
    inner join item_latest i2 on
        i1.id = i2.id
        and i1.occurred = i2.latestoccurred;

它仅抓取occurred的最大occurredid值的项目。