使用查询来更改表映射

时间:2010-05-07 06:49:14

标签: mysql

我有一个表mytable(id,key,value)。我意识到密钥产生了大量的数据冗余,因为我的密钥是一个字符串。 (我的键很长,但是重复)如何构建一个具有(key,keyID)的单独表,然后将我的表替换为mytable(id,keyID,value)和keyTable(keyID,key)?

2 个答案:

答案 0 :(得分:2)

  1. 创建keyTable
  2. mytable填写密钥:

    INSERT INTO keyTable (`key`) SELECT DISTINCT mytable.key FROM mytable;
    
  3. keyID列添加到mytable

  4. 分配keyIDs:

    UPDATE mytable SET keyID = (SELECT keyTable.keyID FROM keyTable WHERE keyTable.key = mytable.key);
    
  5. key

  6. 中删除mytable

答案 1 :(得分:1)

我刚刚为您的问题发布了我的锻炼。请逐步检查:

CREATE TABLE `keytable` (
`keyID` INT( 11 ) NOT NULL auto_increment,
`key` VARCHAR( 100 ) NOT NULL,
`id` INT( 11 ) NOT NULL
) ;

insert into `keytable` (`key`,`id`) select `key`,`id` from mytable;

ALTER TABLE `mytable` CHANGE `key` `keyID` INT( 11 ) NOT NULL ;


update `mytable` set `keyID`= (select `keyID` from keytable where keytable.id=mytable.id)

ALTER TABLE `keytable` DROP `id` ;