理解 FOREIGN KEY / CASCADE 约束时出现问题
我需要一些帮助来理解外键和级联的工作原理。我理解这个理论,但我很难将它们应用到现实世界的例子中。
假设我有以下表格(以及任意数量的可能引用表标签的其他表格):
CREATE TABLE tags (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) UNIQUE
) Engine=InnoDB;
CREATE TABLE news (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(63),
content TEXT,
INDEX (title)
) Engine=InnoDB;
因此,我创建了另一个表格来提供 之间的多对多关系news
和 tags
:
CREATE TABLE news_tags (
news_id INT UNSIGNED,
tags_id INT UNSIGNED,
FOREIGN KEY (news_id) REFERENCES news (id) ON DELETE ...,
FOREIGN KEY (tags_id) REFERENCES tags (id) ON DELETE ...
) Engine=InnoDB;
我对级联的要求:
- 如果我删除新闻,则
news_tags
中的所有相应条目也应该被删除。 - 这同样适用于稍后可能使用
x_tags
-table 添加的表x
。 - 如果我删除标签,则
news_tags
和每个其他表x_tags
中的所有相应条目也应被删除。
我担心我可能必须为此目的重新访问我的表结构,但这没关系,因为我只是想弄清楚东西是如何工作的。
任何优秀教程、SQL 查询或 JPA 示例的链接都值得赞赏!
I need some help at understanding how foreign keys and cascades work. I understood the theory but I'm having troubles to apply these to a real world example.
Let's assume I've got the following tables (and an arbitrary number of other tables that may reference table tags
):
CREATE TABLE tags (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) UNIQUE
) Engine=InnoDB;
CREATE TABLE news (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(63),
content TEXT,
INDEX (title)
) Engine=InnoDB;
So I create a further table to provide the many-to-many relation between news
and tags
:
CREATE TABLE news_tags (
news_id INT UNSIGNED,
tags_id INT UNSIGNED,
FOREIGN KEY (news_id) REFERENCES news (id) ON DELETE ...,
FOREIGN KEY (tags_id) REFERENCES tags (id) ON DELETE ...
) Engine=InnoDB;
My requirements to the cascades:
- If I delete a news, all corresponding entries in
news_tags
should be removed as well. - Same applies for table
x
that may be added later withx_tags
-table. - If I delete a tag, all corresponding entries in
news_tags
and in every further tablex_tags
should be removed as well.
I'm afraid that I may have to revisit my table structure for this purpose, but that's alright since I'm only trying to figure out how stuff works.
Any links to good tutorials, SQL-queries or JPA-examples appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎提出了这样的建议,这对我来说听起来很合理:
You seem to be proposing something like this, which sounds reasonable to me: