gpt4 book ai didi

php - MySQL ON DUPLICATE KEY 插入审计或日志表

转载 作者:可可西里 更新时间:2023-11-01 06:32:57 25 4
gpt4 key购买 nike

有没有办法做到这一点?

INSERT IGNORE INTO some_table (one,two,three) VALUES(1,2,3)
ON DUPLICATE KEY (INSERT INTO audit_table VALUES(NOW(),'Duplicate key ignored')

我真的不想为此使用 PHP :(

谢谢!

最佳答案

如果要考虑使用存储过程,可以使用 DECLARE CONTINUE HANDLER .这是一个例子:

CREATE TABLE users (
username VARCHAR(30),
first_name VARCHAR(30),
last_name VARCHAR(30),
PRIMARY KEY (username)
);

CREATE TABLE audit_table (timestamp datetime, description varchar(255));

DELIMITER $$
CREATE PROCEDURE add_user
(in_username VARCHAR(30),
in_first_name VARCHAR(30),
in_last_name VARCHAR(30))
MODIFIES SQL DATA
BEGIN
DECLARE duplicate_key INT DEFAULT 0;
BEGIN
DECLARE EXIT HANDLER FOR 1062 SET duplicate_key = 1;

INSERT INTO users (username, first_name, last_name)
VALUES (in_username, in_first_name, in_last_name);
END;

IF duplicate_key = 1 THEN
INSERT INTO audit_table VALUES(NOW(), 'Duplicate key ignored');
END IF;
END$$
DELIMITER ;

让我们添加一些数据,尝试插入一个重复的键:

CALL add_user('userA', 'Bob', 'Smith');
CALL add_user('userB', 'Paul', 'Green');
CALL add_user('userA', 'Jack', 'Brown');

结果:

SELECT * FROM users;
+----------+------------+-----------+
| username | first_name | last_name |
+----------+------------+-----------+
| userA | Bob | Smith |
| userB | Paul | Green |
+----------+------------+-----------+
2 rows in set (0.00 sec)

SELECT * FROM audit_table;
+---------------------+-----------------------+
| timestamp | description |
+---------------------+-----------------------+
| 2010-10-07 20:17:35 | Duplicate key ignored |
+---------------------+-----------------------+
1 row in set (0.00 sec)

如果审计在数据库级别很重要,您可能只想授予 EXECUTE 权限,以便您的数据库用户只能调用存储过程。

关于php - MySQL ON DUPLICATE KEY 插入审计或日志表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3884344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com