tags:

views:

53

answers:

2

For the following (simplified) mysql DB setup, I'd like to copy the applicable guids into the message table. Can this be done with a single 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, '');
+7  A: 

UPDATE m SET m.user_guid = u.guid FROM message m INNER JOIN user u ON u.id = m.user

The above was for MS SQL.

For mySQL try this:

UPDATE FROM message as m INNER JOIN user as u ON u.id = m.user
SET m.user_guid = u.guid

Or the latter latter :

UPDATE message as m SET m.user_guid = u.guid
FROM message INNER JOIN user as u ON u.id = m.user
JonH
JonH, thanks for your answer. Although, I wasn't able to get this to work in MySQL 5.1.47-community. Does MySQL support this UPDATE-FROM syntax?
Derek Illchuk
@Derek Illchuk - Try the second update I posted. I think the former is for MS SQL the latter is for mySQL.
JonH
JonH, in either case, my MySQL server didn't like the `FROM ...`. I think the UPDATE-FROM on MySQL is not supported. Again, thank you, here's an up-vote.
Derek Illchuk
@Derek lllchuk - Ok I guess you could try the latter latter :)
JonH
On the latter latter, same error, do'h! But, at least we're in good spirits!
Derek Illchuk
Amazing - and the local instance of mySQL works fine here. I don't know what to tell you but at least you have a solution.
JonH
+2  A: 

Use:

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)
OMG Ponies
That's gonna spin for a good while if the tables are of any significant size...
gms8994
This worked well, and I went with `UPDATE message SET user_guid = (SELECT u.guid FROM user u WHERE u.id = message.user);`.
Derek Illchuk
@gms8994: You think a JOIN changes the fact of having lots of data to update? JOINs in the UPDATE (or DELETE) aren't supported on all databases; this is the logical equivalent to JonH's JOIN query.
OMG Ponies
@OMG Ponies: Logically yes, they're equivalent. But what the engine does behind the scenes is a different story... at least specifically MySQL.
gms8994
@gms8994: So now you're saying it's the optimizer's decision, not the amount of data, that will cause this to "spin for a good while"...
OMG Ponies