简体   繁体   English

在更新级联上添加外键

[英]add foreign key with on update cascade

Let's say, I have 2 tables 假设我有2张桌子

user 用户

+----+--------+
| id | status |
+----+--------+
|  1 | A      |
|  2 | A      |
+----+--------+

article 文章

+----+-----+--------+
| id | uid | status |
+----+-----+--------+
|  1 |   1 | A      |
|  2 |   2 | A      |
|  3 |   2 | A      |
|  4 |   2 | A      |
|  5 |   1 | A      |
|  6 |   2 | A      |
|  7 |   2 | A      |
|  8 |   1 | A      |
|  9 |   2 | A      |
| 10 |   2 | A      |
+----+-----+--------+

How can I add a foreign key that if I run this query: 如果运行此查询,如何添加外键:

UPDATE user SET status='B' WHERE id=1 OR id=2;

the result will be: 结果将是:

user 用户

+----+--------+
| id | status |
+----+--------+
|  1 | B      |
|  2 | B      |
+----+--------+

article 文章

+----+-----+--------+
| id | uid | status |
+----+-----+--------+
|  1 |   1 | B      |
|  2 |   2 | B      |
|  3 |   2 | B      |
|  4 |   2 | B      |
|  5 |   1 | B      |
|  6 |   2 | B      |
|  7 |   2 | B      |
|  8 |   1 | B      |
|  9 |   2 | B      |
| 10 |   2 | B      |
+----+-----+--------+

Or in other words, if I update column user.status , MySQL will automatically update column article.status with the respective value. 换句话说,如果我更新user.status列,MySQL将自动使用相应的值更新article.status列。

How can I create this foreign key? 如何创建此外键?

That job is not foreign key could finish. 该工作不是外键可以完成。 Use an update trigger, but for better Database compatibility, do this action on you code is preferred. 使用更新触发器,但是为了更好地与数据库兼容,最好对代码执行此操作。

Trigger code: 触发码:

CREATE TRIGGER SetArticleStatus AFTER UPDATE ON user 
FOR EACH ROW 
BEGIN 
UPDATE `article` 
   SET status = NEW.status 
 WHERE uid = NEW.id
END 

Since your FOREIGN KEY is only uid and doesn't know about status the thing you want can't be accomplished using only foreign-keys. 由于您的FOREIGN KEY只是uid ,并且不了解status因此仅使用外键就无法完成您想要的事情。 This looks like a good use-case for a on-update-trigger. 对于更新触发,这似乎是一个很好的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM