首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据最新记录更新另一个表

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

Stack Overflow用户
提问于 2015-03-14 15:53:35
回答 3查看 2.8K关注 0票数 0

我有下面的桌子(对不起,我想不出怎么把桌子寄出去.用粗体表示的是字段名)

码desc信道日期

1001 A超级市场10月10日至10月

1001B小插销15-dic

1003 07年5月A餐厅

1003 B bar 30-abr

1003 A餐厅12 dic

1002 B号亭10至10月10日

我试图获取每个代码的最新记录,并将其更新到另一个表中,在该表中,我已经拥有了需要更新的所有代码(在这个表中,我有相同的字段,但需要将它们更新为最新的)。

结果就是

码des信道日期

1001B小插销15-dic

1003 A餐厅12 dic

1002 B号亭1 0-10月

提前感谢您的帮助!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-03-14 16:22:53

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

代码语言:javascript
复制
select t.*
from table as t
where t.date = (select max(t2.date) from table as t2 where t2.code = t.code);

我不知道您的另一个表是什么样子,但是您可以将它修复为如下查询:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2015-03-14 16:05:54

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

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-03-14 16:27:42

我不知道这是不是进入的问题。这与Gordon的回答大致相同,但它也向您展示了如何为多个列编写更新。

代码语言:javascript
复制
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
    )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29050917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档