MySQL将数据从一个表移动到另一个表,匹配ID

时间:2011-11-22 09:22:39

标签: mysql sql

我有(a.o.)两个MySQL表(a.o.)以下列:

tweets:
-------------------------------------
id text        from_user_id from_user
-------------------------------------
1  Cool tweet! 13295354     tradeny
2  Tweeeeeeeet 43232544     bolleke
3  Yet another 13295354     tradeny
4  Something.. 53546443     janusz4

users:
-------------------------------------
id from_user num_tweets from_user_id
-------------------------------------
1  tradeny   2235
2  bolleke   432
3  janusz4   5354

我现在想要对tweets表进行规范化,将tweets.from_user替换为与users.id匹配的整数。其次,我想填写相应的users.from_user_id,最后,我想删除tweets.from_user_id,以便最终结果如下:

tweets:
------------------------
id text        from_user
------------------------
1  Cool tweet!     1
2  Tweeeeeeeet     2
3  Yet another     1
4  Something..     3

users:
-------------------------------------
id from_user num_tweets from_user_id
-------------------------------------
1  tradeny   2235       13295354
2  bolleke   432        43232544
3  janusz4   5354       53546443

我的问题是,是否可以帮助我形成正确的查询。我到目前为止只是来了:

UPDATE tweets SET from_user =
  (SELECT id FROM users WHERE from_user = tweets.from_user)
WHERE...

UPDATE users SET from_user_id =
  (SELECT from_user_id FROM tweets WHERE from_user = tweets.from_user)
WHERE...

ALTER TABLE tweets DROP from_user_id

非常感谢任何帮助: - )

2 个答案:

答案 0 :(得分:1)

我认为这样的事情应该有效:

UPDATE FROM tweets t 
LEFT JOIN users u ON u.from_user = t.from_user
SET t.from_user = u.id

UPDATE FROM users u
LEFT JOIN tweets t ON t.from_user = u.from_user
SET u.from_user_id = t.from_user_id

ALTER TABLE tweets DROP COLUMN from_user_id

答案 1 :(得分:1)

示例工作:

推文表

http://data.stackexchange.com/stackoverflow/s/2144/mysql-move-data-from-one-table-to-another-matching-ids

用户表

http://data.stackexchange.com/stackoverflow/qe/2145/mysql-move-data-from-one-table-to-another-matching-ids

UPDATE users
SET users.from_user_id = tweets.from_user_id
FROM users
LEFT JOIN tweets ON users.from_user = tweets.from_user;

UPDATE tweets
SET tweets.from_user = users.id
FROM tweets
LEFT JOIN users ON tweets.from_user = users.from_user;

ALTER TABLE tweets DROP COLUMN from_user_id;
ALTER TABLE tweets ALTER COLUMN from_user int;

可能的MySQL查询

未经过测试

UPDATE users, tweets
SET users.from_user_id = tweets.from_user_id
WHERE users.from_user = tweets.from_user;

UPDATE tweets, users
SET tweets.from_user = users.id
WHERE tweets.from_user = users.from_user;

ALTER TABLE tweets DROP COLUMN from_user_id;
ALTER TABLE tweets CHANGE COLUMN from_user from_user int;