MySQL触发器-比较两个不同表的值

时间:2018-11-21 13:46:54

标签: mysql triggers phpmyadmin

我目前正在努力在MySQL中实现触发器。 我的情况如下:

有两个数据库( emailregistration和答案),它们具有一组不同的ID作为主键。因此,我想使用电子邮件地址作为标识符来识别需要更新的正确行(在两个表中都相同) 我想在数据库“注册”更新时启动触发器。然后,此触发器将更新“用户”中的值。 (表示为已确认/未订阅

据我了解,问题在于没有检查正确的行。我下面的代码直接采用phpmyadmin形式。该语句以当前形式填充空白行的答案数据库,并根据需要更改已确认/取消订阅的列,但未标识正确的行。

    AFTER
    UPDATE
    ------
    INSERT INTO answers (confirmed, unsubscribed)
    SELECT emailregistration.confirmed, emailregistration.unsubscribed
    FROM emailregistration
    WHERE emailregistration.email = email
    -----
    root@localhost

    *This should translate into the following trigger code:*

    CREATE TRIGGER DOI 
    AFTER UPDATE
    ON emailregistration
    FOR EACH ROW
    BEGIN
    INSERT INTO answers (confirmed, unsubscribed)
    SELECT emailregistration.confirmed, emailregistration.unsubscribed
    FROM emailregistration
    WHERE emailregistration.email = email
    END;

我希望我能准确地描述我的问题。如果我没有,请随时提问。 非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

也许是这样

drop table if exists r,u;
create table r(email varchar(3), subscribed varchar(1), confirmed varchar(1));
create table u(email varchar(3), subscribed varchar(1), confirmed varchar(1));

insert into r (email) values('aaa'),('bbb');
insert into u (email,subscribed,confirmed) values('aaa','x','x'),('bbb','y','y');
drop trigger if exists t;
delimiter $$
CREATE TRIGGER t 
AFTER UPDATE
ON r
FOR EACH ROW
BEGIN
     update u 
        set  subscribed = new.subscribed,
              confirmed = new.confirmed
        where email = new.email;

END $$
delimiter ;

update r set subscribed = 'n' where email = 'aaa';

select * from r;

+-------+------------+-----------+
| email | subscribed | confirmed |
+-------+------------+-----------+
| aaa   | n          | NULL      |
| bbb   | NULL       | NULL      |
+-------+------------+-----------+
2 rows in set (0.00 sec)

select * from u;

+-------+------------+-----------+
| email | subscribed | confirmed |
+-------+------------+-----------+
| aaa   | n          | NULL      |
| bbb   | y          | y         |
+-------+------------+-----------+
2 rows in set (0.00 sec)

如果这不是模型,则将其与预期结果一起添加到问题中。