Mysql

如果存在,則更新 else 插入,儲存過程中的游標僅返回 1 行

  • November 1, 2018

我有 2 個表 api(columns - api, api_context, api_id –> 主鍵) 和 api_request_summary(columns - api_context)。我需要在表 curhittest1 中插入與特定 api_id 相關的 api_context 重複的次數。兩個表都有多行,所以我使用游標遍歷表。我可以正確地將值插入到表中,但我需要檢查 curhittest1 表中是否已經存在 api_id,如果是更新,如果沒有插入。

DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

DECLARE done INT DEFAULT FALSE;
DECLARE apiId, noOfHits int(11);
Declare apiContext varchar(255);

DECLARE cur1 CURSOR FOR Select api_id from api;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;     

 OPEN cur1;

read_loop: LOOP
   FETCH cur1 INTO apiId;

   IF done THEN
     LEAVE read_loop;
   END IF; 

   select api_context into apiContext from api where api_id =apiId;  

   SELECT COUNT(*) FROM api_request_summary WHERE api_context=apiContext into noOfHits;

IF exists (SELECT * FROM curhittest1 WHERE apiid = apiId) THEN

  UPDATE curhittest1
                     SET noofhits=noOfHits                        
                     WHERE apiid = apiId;
ELSE

 insert into curhittest1(apiid,noofhits) values (apiId,noOfHits);
END IF;

 END LOOP;

 CLOSE cur1;

END//
DELIMITER

當我使用以下程式碼時,只有 1 行添加到 curhittest1 表中。當在沒有游標的 sql 過程中使用完全相同的程式碼時,它會顯示,所以我假設在使用游標時我需要做一些不同的事情。如何準確地將所有值添加到表中?

它在使用 INSERT … ON DUPLICATE KEY UPDATE 後起作用。謝謝@RickJames。對於任何對此感興趣的人都是程式碼

DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

DECLARE done INT DEFAULT FALSE;
DECLARE apiId, noOfHits int(11);
Declare apiContext varchar(255);    
DECLARE cur1 CURSOR FOR Select api_id from api;    
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;     

 OPEN cur1;

read_loop: LOOP
   FETCH cur1 INTO apiId;

   IF done THEN
     LEAVE read_loop;
   END IF; 

   select api_context into apiContext from api where api_id =apiId;  

SET noOfHits = (SELECT COUNT(*) FROM api_request_summary 
               WHERE api_context=apiContext);

INSERT INTO api_hits (api_id,no_of_hits) VALUES (apiId,noOfHits)
  ON DUPLICATE KEY UPDATE no_of_hits=noOfHits;

 END LOOP;

CLOSE cur1;

END//
DELIMITER

引用自:https://dba.stackexchange.com/questions/221073