如何根据关联表中的值更新多个列?

时间:2013-08-14 11:31:56

标签: mysql sql sql-update sqldatetime sql-limit

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

-------------------------
 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中找到 可以选择每个记录的最新版本,如本示例所示 masters 记录2

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

如何使用中的最新 更新主张表的每条记录命令?我想覆盖nameadded_at列的值。请注意,版本表中还有其他列,这些列在 masters 表中不存在,例如notes

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

5 个答案:

答案 0 :(得分: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的。

答案 1 :(得分: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;

答案 2 :(得分: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))

答案 3 :(得分: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;

答案 4 :(得分: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);