我有 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。对于任何对此感兴趣的人都是代码