如何在几个表上设置一个FK(外键)? [英] How to set one FK (foreign key) on several tables?

查看:223
本文介绍了如何在几个表上设置一个FK(外键)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个帖子表和一个表决表。如何防止在投票中插入不存在的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆