使用除OLD.id之外的ID触发

时间:2016-12-10 13:12:21

标签: mysql sql triggers sql-delete

我有一张这样的表:

user_oauth

+----------------+-----------------+------+-----+---------+----------------+
| Field          | Type            | Null | Key | Default | Extra          |
+----------------+-----------------+------+-----+---------+----------------+
| id             | int(8) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id        | int(8) unsigned | NO   | MUL | NULL    |                |
| google_id      | varchar(30)     | YES  | UNI | NULL    |                |
| facebook_id    | varchar(30)     | YES  | UNI | NULL    |                |
| windowslive_id | varchar(30)     | YES  | UNI | NULL    |                |
+----------------+-----------------+------+-----+---------+----------------+

包含表格user_facebookuser_googleuser_windowslive

的ID为3

user_facebook 的示例:

+-----------+-----------------+------+-----+---------+-------+
| Field     | Type            | Null | Key | Default | Extra |
+-----------+-----------------+------+-----+---------+-------+
| id        | varchar(30)     | NO   | PRI | NULL    |       |
| email     | varchar(60)     | NO   | UNI | NULL    |       |
| firstname | varchar(30)     | YES  |     | NULL    |       |
| lastname  | varchar(30)     | YES  |     | NULL    |       |
| link      | varchar(100)    | YES  |     | NULL    |       |
| locale    | varchar(5)      | YES  |     | NULL    |       |
| picture   | varchar(200)    | YES  |     | NULL    |       |
| verified  | int(1) unsigned | NO   |     | NULL    |       |
+-----------+-----------------+------+-----+---------+-------+

我想在user_oauth上删除TRIGGER,如果user_facebook填充facebook_id,则会删除user_oauth行。

所以我试过了:

DELIMITER $$
CREATE TRIGGER `user_oauth_delete` BEFORE DELETE ON `user_oauth` 
FOR EACH ROW BEGIN
DELETE FROM user_facebook
    WHERE user_facebook.id = user_oauth.facebook_id;
END
$$
DELIMITER ;

但是我有错误信息: Unknown column 'user_oauth.facebook_id' in 'where clause'

怎么做? 感谢。

解决方案

我误解了OLD声明,所以我不得不:

DELIMITER $$
CREATE TRIGGER `user_oauth_delete` BEFORE DELETE ON `user_oauth` 
FOR EACH ROW BEGIN
DELETE FROM user_facebook
    WHERE user_facebook.id = OLD.facebook_id;
END
$$
DELIMITER ;

2 个答案:

答案 0 :(得分:1)

请勿使用触发器执行此操作。使用级联删除约束来执行此操作。

alter table oath
    add constraint fk_oath_facebook
        foreign key (facebookid) references user_facebook(id)
        on delete cascade;

documentation在解释约束和级联功能方面做得非常好。

答案 1 :(得分:0)

除了建议之外,您还可以考虑将DML语句包装在存储过程中的事务块中,并将a=b&c[d]=e&f[g][h]=i作为参数传递给过程。这样两个操作都会以相同的顺序发生。像

这样的东西
facebook_id