通过从另一个表获取最大值来更新表

时间:2016-02-22 11:03:21

标签: mysql sql

我有以下配置:

CREATE TABLE `extRef` (
  `id` bigint(20) NOT NULL,
  `ref` varchar(100) NOT NULL,
  `extType` tinyint(4) NOT NULL,
  `extId` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

我想有效地从这个表中迁移一些数据

对于到达唯一(extType,extId)对,获取最大Id值。

我已经有以下设置:

CREATE TABLE cleanupTbl(
    retainableId BIGINT(20),
    extId BIGINT(20),
    extType BIGINT(20),
    PRIMARY KEY (retainableId, extId, extType)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO cleanupTbl(extId, extType )
SELECT r.`extId`, r.`extType `
FROM `extRef` r
GROUP BY r.`extType `, r.`extId`
HAVING COUNT(*) > 1;

现在,当我尝试插入Maximum Id时,我尝试了以下设置,但似乎没有因错误而起作用。有人可以帮忙做一份工作声明吗?感谢

UPDATE `cleanupTbl` cl
SET cl.`retainableId` = temp.`largestId`
FROM (
    SELECT MAX(r.`id`) AS largestId
    FROM `extRef` r
    JOIN `cleanupTbl` c
    ON  c.`extId` = r.`extId` AND c.`extType ` = r.`extType `
) temp;

UPDATE cl
SET cl.`retainableId` = MAX(r.`id`)
FROM `cleanupTbl` AS cl
INNER JOIN `extRef` AS r
ON cl.`extId` = r.`extId` AND cl.`extType` = r.`extType`;

1 个答案:

答案 0 :(得分:1)

尝试加入已经过滤的(maxID,extID,extType)表,然后相应地更新:

UPDATE `cleanupTbl` cl
INNER JOIN(SELECT MAX(r.`id`) AS largestId, r.`extId`, r.`extType `
           FROM `extRef` r
           GROUP BY r.`extType `,r.`extId`) temp
ON cl.`extId` = temp.`extId` AND cl.`extType ` = temp.`extType `
SET cl.`retainableId` = temp.`largestId`