我有一个表mytable(id,key,value)。我意识到密钥产生了大量的数据冗余,因为我的密钥是一个字符串。 (我的键很长,但是重复)如何构建一个具有(key,keyID)的单独表,然后将我的表替换为mytable(id,keyID,value)和keyTable(keyID,key)?
答案 0 :(得分:2)
keyTable
从mytable
填写密钥:
INSERT INTO keyTable (`key`) SELECT DISTINCT mytable.key FROM mytable;
将keyID
列添加到mytable
分配keyIDs:
UPDATE mytable SET keyID = (SELECT keyTable.keyID FROM keyTable WHERE keyTable.key = mytable.key);
从key
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` ;