mysql:在重复键(多个唯一,而不是pimary键)上插入〜更新。不起作用

时间:2015-08-27 14:04:24

标签: mysql

      CREATE TABLE IF NOT EXISTS `table` (
      `id` int(11) NOT NULL DEFAULT '0',
      `uniq_id` int(11) NOT NULL DEFAULT '0',
      `uniq_cat` varchar(20) NOT NULL DEFAULT '0',
      `value` varchar(255) NOT NULL
    );

 ALTER TABLE `table`
 ADD PRIMARY KEY (`id`), 
 ADD UNIQUE KEY `uniq_id` (`uniq_id`,`uniq_cat`);

 INSERT INTO `table` (uniq_id, uniq_cat, value) 
 VALUES ("1", "1", "ONE") 
 ON DUPLICATE KEY UPDATE value = value;

 INSERT INTO `table` (uniq_id, uniq_cat, value) 
 VALUES ("1", "1", "TWO") 
 ON DUPLICATE KEY UPDATE value = value;

 SELECT * FROM `table`

给出值=" ONE"
为什么???
在第二次插入时,应该从" ONE"到" TWO"但这不会发生

http://sqlfiddle.com/#!2/e443e/1

1 个答案:

答案 0 :(得分:2)

insert into...ON DUPLICATE KEY存在语法问题。试试这个:

 INSERT INTO `table` (uniq_id, uniq_cat, value) 
 VALUES ("1", "1", "ONE") 
 ON DUPLICATE KEY UPDATE value = values(value);

 INSERT INTO `table` (uniq_id, uniq_cat, value) 
 VALUES ("1", "1", "TWO") 
 ON DUPLICATE KEY UPDATE value = values(value);

<强> SQLFIDDLE DEMO