可能这个问题被多次询问,但不适用于我的情况。
表架构
CREATE TABLE `tasks_taskstatus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`video_status` tinyint(1) NOT NULL,
`creative_status` tinyint(1) NOT NULL DEFAULT '0',
`missing_asset` tinyint(1) NOT NULL,
`is_finished` tinyint(1) NOT NULL,
`share_with_am` tinyint(1) NOT NULL,
`ordering` smallint(6) NOT NULL,
`ready_to_begin` tinyint(1) NOT NULL,
`in_progress` tinyint(1) NOT NULL,
`is_conformed` tinyint(1) NOT NULL,
`order_item_equivalent` varchar(60) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=122 DEFAULT CHARSET=latin1;
我需要在mysql数据库中插入一条记录,如果它还不存在,下面是我试图使用的查询。
INSERT IGNORE INTO `tasks_taskstatus`
SET `name`='Saveout - In Progress',
`video_status`=1,
`creative_status`=0,
`missing_asset`=0,
`is_finished`=0,
`share_with_am`=0,
`ordering`=4,
`ready_to_begin`=0,
`in_progress`=1,
`is_conformed`=0,
`order_item_equivalent`='';
但是每次我运行这个查询时都会创建一条新记录,所以上面的语句出了什么问题?如果不存在,我怎样才能修改上面的查询以插入数据/记录?
答案 0 :(得分:0)
您没有INSERT
id
(这是您的主键),因此AUTO_INCREMENT
启动并生成新ID并插入新记录。
问问自己:MySQL如何知道哪个记录要更新?如果您知道(示例答案可能是“name
”),那么您可以更改密钥,这应该可行。
如果name
和video_status
的组合必须是唯一的,请创建一个额外的密钥:
ALTER TABLE `tasks_taskstatus` ADD UNIQUE(`name`, `video_status`);