我有一个像这样定义的表:
CREATE TABLE `Message` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`user_id` integer NOT NULL,
`user_to` integer NOT NULL,
`top_num` integer NOT NULL,
`priority` smallint NOT NULL,
`error` varchar(120) NOT NULL,
UNIQUE (`user_id`, `user_to`, `top_num`)
);
后来,我添加了另一列msg_type,如下所示:
ALTER TABLE Message ADD COLUMN msg_type SMALLINT(6) NOT NULL DEFAULT 0;
但是,我已经意识到我需要更改原始UNIQUE
约束以包含msg_type
。我试过跑
ALTER TABLE Message
ADD UNIQUE INDEX (`user_id`, `user_to`, `top_num`, `msg_type`);
但INSERT进入我的表仍然失败,错误消息表明这是因为旧唯一性约束失败。
当我在mysql中调用describe Messages
时,我看到以下内容:
+-----------------+----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+----------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | MUL | NULL | |
| user_to | int(11) | NO | MUL | NULL | |
| top_num | int(11) | NO | MUL | NULL | |
| priority | smallint(6) | NO | | NULL | |
| error | varchar(120) | NO | | NULL | |
| msg_type | smallint(6) | NO | | 0 | |
+-----------------+----------------------+------+-----+---------+----------------+
这使得msg_type
似乎不是约束的一部分......如何更改表定义的约束,而不是重新创建表?
答案 0 :(得分:10)
与之前的回答to change foreign key constraint
一样,请使用以下步骤:
第1步:删除旧约束:
ALTER TABLE `Message` DROP INDEX `user_id`;
第2步:添加新内容:
ALTER TABLE `Message` ADD UNIQUE INDEX (
`user_id`,
`user_to`,
`top_num`,
`msg_type`);
使用SHOW CREATE TABLE了解约束名称:
mysql> SHOW CREATE TABLE `Message` ;
| Message | CREATE TABLE `Message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`user_to` int(11) NOT NULL,
`top_num` int(11) NOT NULL,
`priority` smallint(6) NOT NULL,
`error` varchar(120) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`user_to`,`top_num`)
-- ^^^^^^^^^ name
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
如果你检查:
mysql> SHOW INDEX FROM `Message`;
Key_name
user_id
是UNIQUE (user_id ....
假如你写:
ALTER TABLE `Message` ADD UNIQUE INDEX (
`user_to`,
`user_id`,
`top_num`,
`msg_type`);
然后你必须使用user_to
作为:
ALTER TABLE `Message` DROP INDEX `user_to`;
答案 1 :(得分:0)
这是因为您尚未删除已创建的第一个唯一约束。现在,您的桌面上有两个独特的约束。
要删除唯一约束,请查看此帖子 Dropping Unique constraint from MySQL table
答案 2 :(得分:0)
这是因为您要添加唯一索引。请先删除唯一索引,然后添加唯一约束。 DROP INDEX index_name ON table_name
现在添加唯一约束。
ALTER TABLE Message
ADD CONSTRAINT uc_message UNIQUE ((`user_id`, `user_to`, `top_num`, `msg_type`);)
答案 3 :(得分:0)
这是因为您要添加唯一索引。请先删除唯一索引,然后添加唯一约束。
ALTER TABLE Message DROP UNIQUE INDEX user_id you have to drop each index one by one.
现在添加唯一约束。
ALTER TABLE消息
添加约束uc_message UNIQUE({user_id
,user_to
,top_num
,msg_type
);)