2

有两个名为mastersversions的表。版本表保存表在不同时间点的条目。

-------------------------
 masters
-------------------------
 id |  name |  added_at
----+-------+------------
  1 | a-old | 2013-08-13
  2 | b-new | 2012-04-19
  3 | c-old | 2012-02-01
  4 | d-old | 2012-12-24

保证每个主条目至少有一个 版本条目。

---------------------------------------------   
 versions
---------------------------------------------
 id |  name |   added_at | notes | master_id
----+-------+--------------------------------
  1 | a-new | 2013-08-14 | lorem |         1
  1 | a-old | 2013-08-13 | lorem |         1
  2 | b-new | 2012-04-19 | lorem |         2
  3 | c-old | 2012-02-01 | lorem |         3
  4 | d-new | 2013-02-20 | lorem |         4
  5 | d-old | 2012-12-24 | lorem |         4

这些表也可以在这个SQL Fiddle中找到。可以选择每个
记录 的最新版本,如记录示例所示:2

SELECT * FROM versions
WHERE master_id = 2
ORDER BY added_at DESC
LIMIT 1;

如何在一个命令中使用最新版本更新masters表的每条记录?我想覆盖和列的值。请注意, versions表中还有一些其他列在masters表中不存在,例如. nameadded_atnotes

可以使用 a 完成更新,JOIN以便在较大的表上快速执行吗?

4

5 回答 5

1

这可能会满足您的需要:

REPLACE INTO masters
    SELECT v.master_id,v.name,v.added_at 
    FROM versions v 
    WHERE v.added_at = (SELECT MAX(vi.added_at) 
                       FROM versions vi 
                       WHERE  vi.master_id = v.master_id);

请注意,这依赖于主键在 id 上具有主键并且是特定于 MySQL 的。

于 2013-08-14T11:49:11.350 回答
1

无需两次触发子查询。

以下是更新声明

update masters m, (
  select id, name, added_at, master_id 
  from versions 
  order by added_at desc
) V
set
  m.name = v.name, 
  m.added_at = v.added_at     
where v.master_id = m.id;
于 2013-08-14T12:31:02.867 回答
0

现在无法在 mysql 上测试它,但这应该适用于 MSSQL

UPDATE masters AS m
SET 
  m.name = 
     (SELECT v.Name FROM versions AS v WHERE v.id = m.id AND v.added_at = 
     (SELECT MAX(v2.added_at) FROM versions As v2 WHERE v2.id = v.id))
  m.added_at = 
     (SELECT v.added_at FROM versions AS v3 WHERE v3.id = m.id AND v3.added_at = 
     (SELECT MAX(v4.added_at) FROM versions As v4 WHERE v4.id = v3.id))
于 2013-08-14T11:48:40.487 回答
0
update masters set 
name = (SELECT name FROM versions
       WHERE master_id = masters.id
       ORDER BY added_at DESC
       LIMIT 1),
added_at = (SELECT added_at FROM versions
        WHERE master_id = masters.id
        ORDER BY added_at DESC
        LIMIT 1)
where id = 2;
于 2013-08-14T11:59:17.557 回答
0

这可能对你有用,试试这个:

UPDATE masters m 
SET m.name = (SELECT v.name FROM versions v WHERE
m.id = v.master_id ORDER BY v.added_at DESC LIMIT 1), 
m.added_at =
(SELECT v.added_at FROM versions v WHERE m.id = v.master_id ORDER BY
v.added_at DESC LIMIT 1);
于 2013-08-14T12:01:01.110 回答