我有这样的Mysql表
CREATE TABLE IF NOT EXISTS tbl_member_doc_read ( `read_id` INTEGER(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT , `member_id` INTEGER(10) UNSIGNED NOT NULL , `doc_id` INTEGER(10) UNSIGNED NOT NULL , `status` INTEGER(1) DEFAULT '0', FOREIGN KEY (`member_id`) REFERENCES tbl_member(`member_id`), FOREIGN KEY (`doc_id`) REFERENCES tbl_doc(`doc_id`) ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
假设该表的示例数据ID
read_id member_id doc_id status 1 1 1 1 2 1 2 0 3 2 2 1
现在,如果组合或对(member_id,doc_id)存在,我想在该表中插入;否则,如果status为0,则更新状态。这是我使用的sql查询
INSERT INTO tbl_member_doc_read (member_id, doc_id, status) VALUES(1,2,1) ON DUPLICATE KEY UPDATE status = VALUES(status) WHERE status = 0;
它应该用数据2 1 2 1更新第二行
如果我插入这个
INSERT INTO tbl_member_doc_read (member_id, doc_id, status) VALUES(2,1,0) ON DUPLICATE KEY UPDATE status = VALUES(status) WHERE status = 0;
它应该插入一个新行,其数据为4 2 1 0
但我无法解决。而且我认为在innodb引擎中,member_id和doc_id被引用到另一个表的主键,它们是唯一的。在innodb中,我无法创建唯一索引。
任何帮助将不胜感激。提前致谢。
为了处理该ON DUPLICATE KEY UPDATE语句,您需要unique在两列上定义键,
ON DUPLICATE KEY UPDATE
unique
CREATE TABLE IF NOT EXISTS tbl_member_doc_read ( `read_id` INTEGER(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT , `member_id` INTEGER(10) UNSIGNED NOT NULL , `doc_id` INTEGER(10) UNSIGNED NOT NULL , `status` INTEGER(1) DEFAULT '0', FOREIGN KEY (`member_id`) REFERENCES tbl_member(`member_id`), FOREIGN KEY (`doc_id`) REFERENCES tbl_doc(`doc_id`), CONSTRAINT tb_uq UNIQUE (member_id, doc_id) ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
然后删除该WHERE子句
WHERE
INSERT INTO tbl_member_doc_read (member_id, doc_id, status) VALUES(1,2,1) ON DUPLICATE KEY UPDATE status = VALUES(status)