您可以利用MySQL TRIGGERS来自动执行此操作。
CREATE TRIGGER after_insert_wp_users
AFTER INSERT ON wp_users FOR EACH ROW
BEGIN
INSERT INTO forum_users (username, password, email)
VALUES (NEW.username, NEW.password, NEW.email);
END
您可以对 UPDATE 和其他查询执行相同的操作。
编辑1:
如果两个表都需要自动更新,即如果在表中插入一行wp_users
,则自动插入,forum_users
反之亦然,编写第二组触发器以从 forum_users 更新 wp_users 表将引入递归循环。
为了避免这种情况,我们可以使用状态变量来检查是否应该进行二次插入。
触发器 1:
CREATE TRIGGER after_insert_wp_users
AFTER INSERT ON wp_users FOR EACH ROW
BEGIN
IF @__disable_trigger_users = 1 THEN
SET @__disable_trigger_users = NULL;
ELSE
SET @__disable_trigger_users = 1;
INSERT INTO forum_users (username, password, email)
VALUES (NEW.username, NEW.password, NEW.email);
END IF;
END
触发器 2:
CREATE TRIGGER after_insert_forum_users
AFTER INSERT ON forum_users FOR EACH ROW
BEGIN
IF @__disable_trigger_users = 1 THEN
SET @__disable_trigger_users = NULL;
ELSE
SET @__disable_trigger_users = 1;
INSERT INTO wp_users (username, password, email)
VALUES (NEW.username, NEW.password, NEW.email);
END IF;
END
已编辑 2
您也可以使用MySQL Store Procedure实现相同的目的。
DROP PROCEDURE IF EXISTS proc_insert_user
GO
CREATE PROCEDURE proc_insert_user
(
IN p_username VARCHAR(15),
IN p_password VARCHAR(15),
IN p_email VARCHAR(15)
)
BEGIN
INSERT INTO wp_users (username, password, email)
VALUES (p_username, p_password, p_email);
INSERT INTO forum_users (username, password, email)
VALUES (p_username, p_password, p_email);
END
GO
CALL proc_insert_user('$_POST[username]', '$_POST[password]', '$_POST[email]')
GO