UPDATE cell value if a pair matches

时光毁灭记忆、已成空白 提交于 2020-01-06 02:33:10

问题


I am using luasql. I have two tables of this type:

IPINFO

CREATE TABLE `ipstats` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(15) NOT NULL,
  `last_used` DATETIME NOT NULL DEFAULT '1981-09-30 00:00:00',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `ip` (`ip`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
ROW_FORMAT=DEFAULT

and another table ipnstats:

CREATE TABLE `ipnstats` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ipstats_id` INT(10) UNSIGNED NOT NULL,
  `nick` VARCHAR(32) NOT NULL,
  `used_times` INT(10) UNSIGNED NOT NULL,
  `last_used` DATETIME NOT NULL DEFAULT '1981-09-30 00:00:00',
  PRIMARY KEY (`id`),
  INDEX `ipstats_id` (`ipstats_id`),
  INDEX `nick` (`nick`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
ROW_FORMAT=DEFAULT

Now, what I am trying to achieve here is that in my ipnstats table, the value of used_times will be updated IFF(if and only if) both the indexes(nickname and ipstats_id) in the table are matched. My insertion/updation command goes like this:

INSERT INTO `ipstats_nicks` (`ipstats_id`, `nick`, `last_used`) 
  VALUES ( %d, '%s', '%s' ) 
  ON DUPLICATE KEY 
  UPDATE `last_used` = '%s', `used_times` = `used_times`+1

and then I am formatting this string using variables. But this is not giving me the desired update in table. It is just keeping on inserting data into the table.

Any help is appreciated.


回答1:


There are two problems:

  1. ON DUPLICATE KEY UPDATE only works for UNIQUE indexes. Your indexes are not unique.
  2. If any single index gives a conflict, it will perform an update. There's no way to tell it to only perform an update when both indexes have a conflict.

Perhaps what you really want is a single unique multi-column index?

UNIQUE INDEX `ipstats_id_nick` (`ipstats_id`, `nick`)


来源:https://stackoverflow.com/questions/11171354/update-cell-value-if-a-pair-matches

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