我有下面的桌子(对不起,我想不出怎么把桌子寄出去.用粗体表示的是字段名)
码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月
提前感谢您的帮助!
发布于 2015-03-14 16:22:53
您可以使用查询获得结果:
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。
发布于 2015-03-14 16:05:54
另一个答案(其他人也发布了工作)是使用一个临时表。它确实需要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;不知道这是不是更快。
发布于 2015-03-14 16:27:42
我不知道这是不是进入的问题。这与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
)https://stackoverflow.com/questions/29050917
复制相似问题