将列链接到不同的表

时间:2013-09-07 22:07:40

标签: php mysql

好吧所以我认为这不可能,但我要求确定。假设我有一个名为wp_users和forum_users的表。在wp_users中有一个用户名,电子邮件和md5哈希列。与forum_users一样。有没有办法同步两个这样的方式,如

INSERT INTO wp_users (username, password, email)
VALUES ('$_POST[username]', '$_POST[password]', '$_POST[email]'); 

会自动执行

INSERT INTO forum_users (username, password, email)
VALUES ('$_POST[username]', '$_POST[password]', '$_POST[email]'); 

与ALTER等相同。

2 个答案:

答案 0 :(得分:0)

使用交易

BEGIN
 INSERT INTO wp_users (username, password, email)
 VALUES ('$_POST[username]', '$_POST[password]', '$_POST[email]');
 INSERT INTO forum_users (username, password, email)
 VALUES ('$_POST[username]', '$_POST[password]', '$_POST[email]'); 
COMMIT;

答案 1 :(得分:0)

您可以使用 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商店程序 来实现相同目标。

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