对于以下(简化的)mysql数据库设置,我想将适用的guid复制到message
表中。可以使用单个SQL update
完成吗?
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`guid` varchar(13) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `user` (`id`, `guid`) VALUES
(1, 'a'),
(2, 'b'),
(3, 'c');
CREATE TABLE IF NOT EXISTS `message` (
`user` int(11) NOT NULL,
`user_guid` varchar(13) NOT NULL,
KEY `user` (`user`)
) ENGINE=InnoDB;
ALTER TABLE `message`
ADD CONSTRAINT `message_ibfk_1` FOREIGN KEY (`user`) REFERENCES `user` (`id`) ON DELETE CASCADE;
INSERT INTO `message` (`user`, `user_guid`) VALUES
(3, ''),
(2, ''),
(3, '');
答案 0 :(得分:7)
UPDATE m SET m.user_guid = u.guid
FROM message m INNER JOIN用户u ON u.id = m.user
以上是MS SQL。
对于mySQL,试试这个:
UPDATE FROM message as m INNER JOIN user as u ON u.id = m.user
SET m.user_guid = u.guid
或后者:
UPDATE message as m SET m.user_guid = u.guid
FROM message INNER JOIN user as u ON u.id = m.user
答案 1 :(得分:2)
使用:
UPDATE MESSAGE
SET user_guid = (SELECT u.guid
FROM USER u
WHERE u.id = MESSAGE.user)
WHERE EXISTS(SELECT NULL
FROM USER u
WHERE u.id = MESSAGE.user)