鉴于您提到的表格设计:
CREATE TABLE mydb.mytable
(
id int not null auto_increment,
type varchar(35),
data varchar(2000),
primary key (id)
);
您最好的机会如下:
CREATE TABLE mydb.mytable_new LIKE mydb.mytable;
ALTER TABLE mydb.mytable_new ADD COLUMN data_hash CHAR(40);
ALTER TABLE mydb.mytable_new ADD UNIQUE INDEX (data_hash);
INSERT INTO mydb.mytable_new (id,type,data,data_hash)
SELECT id,type,data,UPPER(SHA(data)) FROM mydb.mytable;
ALTER TABLE mydb.mytable RENAME mydb.mytable_old;
ALTER TABLE mydb.mytable_new RENAME mydb.mytable;
DROP TABLE mydb.mytable_old;
添加此新列和索引后,表现在应如下所示:
CREATE TABLE mydb.mytable
(
id int not null auto_increment,
type varchar(35),
data varchar(2000),
data_hash char(40),
primary key (id),
unique key data_hash (data_hash)
);
只需执行以下操作:
插入
INSERT INTO mydb.mytable (type,data,data_hash)
VALUES ('somtype','newdata',UPPER(SHA('newdata')));
如果您尝试重复键插入,则 INSERT 应该在 data_hash 上失败
选择
SELECT * FROM mydb.mytable
WHERE data_hash = UPPER(SHA('data_I_am_searching_for'));
试试看 !!!