Mysql:是否有一个更新语句将按如下方式进行非规范化?

时间:2010-09-13 17:23:01

标签: sql mysql

对于以下(简化的)mysql数据库设置,我想将适用的guid复制到message表中。可以使用单个SQL update完成吗?

alt text

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, '');

2 个答案:

答案 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)