【问题标题】:Update another table based on latest record根据最新记录更新另一个表
【发布时间】:2015-03-14 15:53:35
【问题描述】:

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

code desc 频道日期

1001 超市 10-oct

1001 B minimarket 15-dic

1003 餐厅 07-5 月

1003 B 酒吧 30-abr

1003 餐厅 12-dic

1002 B 信息亭 10-oct

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

结果是这样的

频道日期代码

1001 B minimarket 15-dic

1003 餐厅 12-dic

1002 B 信息亭 1 0-oct

提前感谢您的帮助!

【问题讨论】:

  • 您是否有真实的日期或字符串,如图所示?有了真实日期,您可以使用 Max。
  • 为什么要这样存储日期。始终使用正确的数据类型,这将解决您的问题
  • 使用主键字段会更容易。有吗?
  • @Fionnuala:日期是真实的。我粘贴在excel中检查,然后在这里重新粘贴... excel可能已将其转换为这种格式。
  • @hpf:第二张表的主键是代码。在源表中没有,因为它以不同的日期出现......

标签: sql ms-access


【解决方案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】:

    另一个答案(正如其他人发布的工作一样)是使用临时表。它确实需要 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;
    

    不确定这是否更快。

    【讨论】:

      【解决方案3】:

      我不知道这是否是 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
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        相关资源
        最近更新 更多