我有以下配置:
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;
现在,当我尝试插入最大 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`;
最佳答案
尝试加入已过滤的(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`
关于mysql - 通过从另一个表获取最大值来更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551951/