为什么我们需要使用外键? [英] Why do we need to use Foreign Keys?
问题描述
可能重复:
我应该使用外键吗?
好吧,让我们假设我们有两个表,用户
和注释
。在注释中,我们有一个列 comment_made_by_user_id
,它意味着哪个用户键入了特定的注释。为什么我们需要将其指定为外键?如果我们不这样做,它仍然会工作。我们指定了主键,因为就我所知,我们只需要搜索一行,而当我们没有主键/索引时,我们必须遍历所有的行。这只是一个很好的编码习惯吗?
当您使用外键时,您将获得:
- 数据完整性
- 查询速度更快。
用户:
用户名称:
user:
Possible Duplicate:
Should I use foreign keys?
Ok, let's assume we have two tables, users
and comments
. In comments we have a column comment_made_by_user_id
and it means which user typed that particular comment. Why do we need to specify it as a foreign key? If we don't do that, it will still work. We specify primary keys, because it makes queries faster as far as I know (we need to search only for one row while when we don't have a primary key/index, we have to go through all rows). Is it just a good coding practise?
When you use foreign keys you get:
- Data integrity
- faster queries.
users:
user id:
- 1
- 2
- 3
Comments:
user:
- 1
- 2
- 4 XXX invalid as 4 isn't in the users table.
Read Wikipedia please for more details about Data integrity
这篇关于为什么我们需要使用外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!