I
I
Igor Samokhin2012-07-19 19:19:15
MySQL
Igor Samokhin, 2012-07-19 19:19:15

How to make on duplicate key "for multiple keys"?

Hello,

CREATE TABLE `user_notification` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `user_id` int(10) unsigned NOT NULL,
  `article_id` int(10) unsigned default NULL,
  `magazine_id` int(10) unsigned default NULL,
  `user_page_id` int(10) unsigned default NULL,
  `date_time` datetime NOT NULL,
  `unix_date` int(10) unsigned NOT NULL,
  `comment_id` int(10) unsigned NOT NULL,
  `is_subscribed` enum('1','0') collate utf8_unicode_ci NOT NULL,
  `status` enum('send','not_send') collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `user_id` (`user_id`,`article_id`,`magazine_id`,`user_page_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

How can I make update only if there are the same values ​​in the columns: `user_id`, `article_id`, `magazine_id`, `user_page_id`
for example, there are already these fields with values:
1, 2, NULL, NULL
and I do
INSERT INTO `user_notification`
  (`user_id`,`article_id`,`magazine_id`,`user_page_id`,`date_time`,`unix_date`,`comment_id`,`is_subscribed`,`status`)
  values 
  (1,2,NULL,NULL,NOW(),UNIX_TIMESTAMP(),3,'1','not_send') 
  ON DUPLICATE KEY UPDATE
  `date_time` = NOW()
  , unix_date = UNIX_TIMESTAMP()
  , comment_id = 4

and the update branch should be executed in the request,
and if there are differences in at least one of these fields, then insert would be executed ...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
sdevalex, 2012-07-19
@sdevalex

Create a unique index for 4 fields...

alter table user_notification add unique index(`user_id`,`article_id`,`magazine_id`,`user_page_id`);

I
ivnik, 2012-07-19
@ivnik

As far as I know ON DUPLICATE KEY UPDATE only works with PRIMARY KEY. Those. to use this feature you will have to put all these fields in the PK.

I
Igor Samokhin, 2012-07-19
@grigor007

horror, everything went .., I'm sorry ...

I
ivnik, 2012-07-19
@ivnik

It is necessary to remove the id field from the PK, i.e. For ON DUPLICATE KEY UPDATE to work, a PK conflict must occur.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question