开发者

Mysql primary key when using INSERT INTO ... ON DUPLICATE KEY UPDATE

My table structure is:

CREATE TABLE IF NOT EXISTS `users_settings_temp` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userid` int(10) unsigned DEFAULT NULL,
  `type` enum('type1','type2')
  `data` text,
  `date_created` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

What I am trying to do is:

Let say I want to insert a new entry, but I dont want it to be duplicate, after google around, i found this format:

INSERT INTO users_settings_temp(...)
ON DUPLICATE KEY UPDATE data = '{$data}'

I guess the problem is in my table, the primary key => id. How do I alter the table, so that I could use the:

INSERT INTO ... ON DUPLICATE KEY UPDATE

Can I use user_id + type as开发者_JS百科 primary key? If yes, could you please show me how to do it?


CREATE TABLE IF NOT EXISTS `users_settings_temp` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userid` int(10) unsigned DEFAULT NULL,
  `type` enum('type1','type2'),
  `data` text,
  `date_created` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`, `type`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

When you do it like this then

a) specifying id works

mysql> INSERT INTO users_settings_temp VALUES (1, 2, 'type1', 'keks', 5);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO users_settings_temp VALUES (1, 2, 'type2', 'keks', 5);
Query OK, 1 row affected (0.00 sec)

b) of course primary key is guaranteed to be unique

mysql> INSERT INTO users_settings_temp VALUES (1, 2, 'type2', 'keks', 5);
ERROR 1062 (23000): Duplicate entry '1-type2' for key 'PRIMARY'

c) letting database pull a new id works

mysql> INSERT INTO users_settings_temp VALUES (NULL, 2, 'type2', 'keks', 5);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO users_settings_temp VALUES (NULL, 2, 'type1', 'keks', 5);
Query OK, 1 row affected (0.00 sec)

but will increase them always

mysql> SELECT * FROM users_settings_temp;
+----+--------+-------+------+--------------+
| id | userid | type  | data | date_created |
+----+--------+-------+------+--------------+
|  1 |      2 | type1 | keks |            5 |
|  1 |      2 | type2 | keks |            5 |
|  2 |      2 | type2 | keks |            5 |
|  3 |      2 | type1 | keks |            5 |
+----+--------+-------+------+--------------+
4 rows in set (0.00 sec)

NOTES:

You should think if your id should still be autoincrement or not. Also, can not think of a reason why date_created should be int(11) instead of datetime

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜