Let's say, I have 2 tables
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.
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. This looks like a good use-case for a on-update-trigger.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.