1

直接来自手册,这是PostgreSQL 中 merge_db 的规范示例

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- Do nothing, and loop to try the UPDATE again.
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

这可以表示为 MySQL 中的用户定义函数,如果可以,如何表示?与 MySQL 的标准相比有什么优势INSERT...ON DUPLICATE KEY UPDATE吗?

注意:我专门寻找用户定义的函数,而不是INSERT...ON DUPLICATE KEY UPDATE.

4

1 回答 1

5

在 MySQL 5.5.14 上测试。

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

DELIMITER //
CREATE PROCEDURE merge_db(k INT, data TEXT) 
BEGIN
    DECLARE done BOOLEAN;
    REPEAT
        BEGIN
            -- If there is a unique key constraint error then 
            -- someone made a concurrent insert. Reset the sentinel
            -- and try again.
            DECLARE ER_DUP_UNIQUE CONDITION FOR 23000;
            DECLARE CONTINUE HANDLER FOR ER_DUP_UNIQUE BEGIN
                SET done = FALSE;
            END;

            SET done = TRUE;
            SELECT COUNT(*) INTO @count FROM db WHERE a = k;
            -- Race condition here. If a concurrent INSERT is made after
            -- the SELECT but before the INSERT below we'll get a duplicate
            -- key error. But the handler above will take care of that.
            IF @count > 0 THEN 
                UPDATE db SET b = data WHERE a = k;
            ELSE 
                INSERT INTO db (a, b) VALUES (k, data);
            END IF;
        END;
    UNTIL done END REPEAT;
END//

DELIMITER ;

CALL merge_db(1, 'david');
CALL merge_db(1, 'dennis');

一些想法:

  • 您不能先进行更新然后检查@ROW_COUNT(),因为它返回实际更改的行数。如果该行已经具有您尝试更新的值,则该值可能为 0。
  • 此外,@ROW_COUNT()复制不是安全的。
  • 你可以使用REPLACE...INTO.
  • 如果使用 InnoDB 或具有事务支持的表,您可能可以使用SELECT...FOR UPDATE(未​​经测试)。

我认为此解决方案与仅使用INSERT...ON DUPLICATE KEY UPDATE.

于 2012-07-07T04:15:29.360 回答