MYSQL Duplicate Key Not Working

末鹿安然 提交于 2019-12-13 02:46:02

问题


Why is my ON DUPLICATE KEY UPDATE statement not working, I am after a way to not have duplicates in my table. With the below code I get duplicates

CMS::insertQuery("INSERT INTO {table} SET canid=?, categoryid=? ON DUPLICATE KEY UPDATE canid=?, categoryid=?", array($emailCheck['id'], $id, $emailCheck['id'], $id));

DB:

CREATE TABLE `table` (  `canid` int(10) NOT NULL,  `categoryid` int(10) NOT NULL,  UNIQUE KEY `canid` (`canid`,`categoryid`)) ENGINE=MyISAM DEFAULT CHARSET=latin1

Current Line I am trying to run:

CMS::insertQuery("INSERT INTO {table} SET canid=?, categoryid=? ON DUPLICATE KEY UPDATE canid=?, categoryid=? WHERE canid=?, categoryid=?", array($emailCheck['id'], $id, $emailCheck['id'], $id,$emailCheck['id'],$id));

回答1:


This is just a guess since you haven't provided your schema, but is one of the columns in your unique key nullable?

Edit:

As @G-Nugget says in the comments, you need a unique key on the columns in question:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.

http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

You need to have a unique key on the combination of columns that should be unique.

eg:

ALTER TABLE yourTable ADD UNIQUE KEY (`canid`, `categoryid`);

Also, when asking database questions, please include SHOW CREATE TABLE for the tables in question.




回答2:


First thing to note, the field on which you would like to check for duplicate should be primary or unique. I was having the same issue and solved now.

http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html



来源:https://stackoverflow.com/questions/12539757/mysql-duplicate-key-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!