使用 INSERT INTO ... ON DUPLICATE KEY UPDATE 时的 Mysql 主键
我的表结构是:
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 ;
我想做的是:
假设我想插入一个新条目,但我不希望它重复,经过谷歌搜索后,我发现了这种格式:
INSERT INTO users_settings_temp(...)
ON DUPLICATE KEY UPDATE data = '{$data}'
我猜问题出在我的表中,主键 => id
。如何更改表,以便可以使用:
INSERT INTO ... ON DUPLICATE KEY UPDATE
我可以使用 user_id + type 作为主键吗?如果是,您能告诉我该怎么做吗?
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 primary key? If yes, could you please show me how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你这样做时,
a)指定id有效
b)当然主键保证是唯一的
c)让数据库提取一个新的id有效,
但总是会增加它们
注意:
你应该考虑如果您的
id
应该仍然是自动增量或不是。另外,想不出为什么
date_created
应该是int(11)
而不是datetime
When you do it like this then
a) specifying id works
b) of course primary key is guaranteed to be unique
c) letting database pull a new id works
but will increase them always
NOTES:
You should think if your
id
should still be autoincrement or not.Also, can not think of a reason why
date_created
should beint(11)
instead ofdatetime