我想用这些字段在MySQL表上提供UPSERTUPDATE如果存在,否则插入):

CREATE TABLE item (
  uid int(11) NOT NULL AUTO_INCREMENT,
  timestamp int(11) NOT NULL DEFAULT '0',
  category1 int(11) NOT NULL DEFAULT '0',
  category2 int(11) NOT NULL DEFAULT '0',
  counter int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`uid`)
)

此表已在生产中使用,(timestamp,category1,category2)的组合是针对myINSERT唯一的,而不是针对整个表内容。这就是我不能使用“ON DUPLICATE KEY”功能的原因。
关于这一独特问题的澄清:
如果category1=9,则这是我的插入,并且(timestamp,category1,category2)是唯一的。但该表正在生产性使用中,如果category1=1,2,则(timestamp,category1,category2)不是唯一的。
据我所知,我不能添加一个UNIQUE键,因为它会对类别1+2造成问题。
我需要的是这样的东西:
 IF (timestamp,category1,category2) exists
     counter=existingCount + newCount
 ELSE
     insert new record

我使用PHP和MySQL,所以两种语言的任何组合都可以。
我已经试过了,但是花了太多时间:
单个PHPSELECT语句,然后UPDATEINSERT
INSERT然后所有行都重复
由于我现在创建了此存储过程的答案,语法正常,但过程不起作用:
DROP PROCEDURE IF EXISTS myUpsert;
DELIMITER |
CREATE PROCEDURE myUpsert (IN v_timestamp INT, IN v_category1 INT, IN v_category2 INT, IN v_counter INT)
BEGIN
  DECLARE existingCounter INT;
  SELECT COUNT(counter) AS existingCounter from item
  WHERE timestamp =v_timestamp  AND category1=v_category1 AND category2=v_category2;

  IF existingCounter=0 THEN
    INSERT INTO item (timestamp,category1,category2,counter)
    VALUES (v_timestamp,v_category1,v_category2,v_counter);
  ELSE
    UPDATE item SET count=v_counter+existingCounter
    WHERE timestamp=v_timestamp AND category1=v_category1 AND category2=v_category2;
  END IF;
END
|
DELIMITER ;

最佳答案

DROP PROCEDURE IF EXISTS myUpsert;
DELIMITER |
CREATE PROCEDURE myUpsert (IN v_timestamp INT, IN v_category1 INT, IN v_category2 INT, IN v_counter INT)
BEGIN
DECLARE existingCounter INT;
  SET existingCounter = (SELECT COUNT(counter) from item
  WHERE timestamp =v_timestamp  AND category1=v_category1 AND category2=v_category2);

IF existingCounter=0 THEN
 INSERT INTO item (timestamp,category1,category2,counter)
 VALUES (v_timestamp,v_category1,v_category2,v_counter);
ELSE
 UPDATE item SET count=v_counter+existingCounter
 WHERE timestamp=v_timestamp AND category1=v_category1 AND category2=v_category2;
 END IF;
END
|
DELIMITER ;

关于php - 没有UP DUPLICATE KEY的MySQL UPSERT,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22639414/

10-09 18:46