根据最新记录更新另一个表

时间:2015-03-14 15:53:36

标签: sql ms-access

我有下表(抱歉无法弄清楚如何发布表格...粗体是字段名称)

代码desc频道日期

1001超市10-oct

1001 B minimarket 15-dic

1003 07-a餐厅

1003 B bar 30-abr

1003餐厅12-dic

1002 B信息亭10-oct

我正在尝试获取每个代码的最新记录并在另一个表中更新它,我已经需要更新所有代码(在此表中我有相同的字段但需要将它们更新到最新)

结果将是这个

代码渠道日期

1001 B minimarket 15-dic

1003餐厅12-dic

1002 B信息亭1 0-oct

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

另一个答案(正如其他人发布的工作一样)是使用临时表。它确实需要3个SQL语句,但可能比下面的嵌套查询更快:

(假设您拥有的两个表称为t1和t2,我使用MySQL)

CREATE TEMPORARY TABLE t3 AS
SELECT code, descr, channel, MAX(date) as mxdate  <--- I would avoid using "desc" and "date" if possible
FROM t1
GROUP BY code;

UPDATE t2,t3
SET t2.descr=t3.descr, t2.channel=t3.channel, t2.date=t3.mxdate
WHERE t2.code=t3.code;

DROP TEMPORARY TABLE t3;

不确定这是否更快。

答案 1 :(得分:1)

您可以使用查询获取结果:

select t.*
from table as t
where t.date = (select max(t2.date) from table as t2 where t2.code = t.code);

我不确定你的其他表是什么样的,但你可以将其修复为如下的查询:

update secondtable
    set val = (select channel
               from table as t
               where t.code = secondtable.code and
                     t.date = (select max(t2.date) from table as t2 where t2.code = t.code)
             );

如果设置了多个字段,您还可以使用join

答案 2 :(得分:0)

我不知道这是否是Access的问题。它与Gordon的答案几乎相同,但它也向您展示了如何为多列编写更新。

update T2
set desc = (
        select t.desc
        from T as t inner join
            (select code, max(date) as maxdate ftom t group by code) as m
            on m.code = t.code and m.maxdate = t.date
        where t.code = T2.code
    ),
    channel = (
        select t.channel
        from T as t inner join
            (select code, max(date) as maxdate ftom t group by code) as m
            on m.code = t.code and m.maxdate = t.date
        where t.code = T2.code
    ),
    date = (
        select t.date
        from T as t inner join
            (select code, max(date) as maxdate ftom t group by code) as m
            on m.code = t.code and m.maxdate = t.date
        where t.code = T2.code
    )