如何在几个表上设置一个FK(外键)? [英] How to set one FK (foreign key) on several tables?
问题描述
我有几个帖子
表和一个表决
表。如何防止在投票中插入不存在的
post_id
(在 / code>表?
// Posts_1 // Posts_2 // Posts_3
+ + --------- + + ---- + --------- + + ---- + --------- +
| id |内容| | id |内容| | id |内容|
+ ---- + --------- + + ---- + --------- + + ---- + -------- - +
//投票
+ ---- + --------- +
| id | post_id |
+ ---- + --------- +
应该注意,实际上 Posts
表的结构不同。 (所有 Posts
表具有不同的结构),然后我不能将所有 posts
表合并为一个表。 / p>
现在我想防止在 Votes
表中插入无效行。 (无效= post_id
不存在于帖子
表中)
所以,如果我只有一个表,我可以在 Votes.post_id
上创建一个外键 Posts.id
,但问题是有几个 posts
表。好的,有什么建议吗?
表结构是疯狂的。你需要一个POST索引表,它将所有的帖子合并到一个地方,并给出如下:
// Posts_Index
+ ---- + --------- + ------------ +
| id | post_id | post_table |
+ ---- + --------- + ------------ +
//投票
+ - --- + --------- +
| id | post_id |
+ ---- + --------- +
你需要反向映射的方式。所以, post_id - > votes.id
。
I have several Posts
tables and one Votes
table. How can I prevent inserting non-existing post_id
(in Posts
tables) in the Votes
table?
// Posts_1 // Posts_2 // Posts_3
+----+---------+ +----+---------+ +----+---------+
| id | content | | id | content | | id | content |
+----+---------+ +----+---------+ +----+---------+
// Votes
+----+---------+
| id | post_id |
+----+---------+
It should be noted, in reality the structure of Posts
tables is different. (all Posts
tables have not the same structure), Then I can not combine all Posts
tables as one table.
Now I want to prevent of inserting invalid rows in the Votes
table. (invalid = post_id
is not exist in the none of Posts
tables)
So, If I have just one table, I can create a foreign key on the Votes.post_id
reference to Posts.id
, But the problem is having several Posts
table. ok, well, Is there any suggest?
The table structure is crazy. You need to have a POST Index Table, which combines all the posts to one single place and gives it like this:
// Posts_Index
+----+---------+------------+
| id | post_id | post_table |
+----+---------+------------+
// Votes
+----+---------+
| id | post_id |
+----+---------+
Else you need to reverse map the way. So that, post_id -> votes.id
.
这篇关于如何在几个表上设置一个FK(外键)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!