为什么我们需要使用外键? [英] Why do we need to use Foreign Keys?

查看:211
本文介绍了为什么我们需要使用外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我应该使用外键吗?


好吧,让我们假设我们有两个表,用户注释。在注释中,我们有一个列 comment_made_by_user_id ,它意味着哪个用户键入了特定的注释。为什么我们需要将其指定为外键?如果我们不这样做,它仍然会工作。我们指定了主键,因为就我所知,我们只需要搜索一行,而当我们没有主键/索引时,我们必须遍历所有的行。这只是一个很好的编码习惯吗?

解决方案

当您使用外键时,您将获得:


  1. 数据完整性

  2. 查询速度更快。

用户:

用户名称:


  • 1
  • $ b

    user:



    • 1

    • 2

    • 4 XXX无效,因为4不在用户表中。
    • strong> Wikipedia
      请详细了解数据完整性


      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:

      1. Data integrity
      2. 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屋!

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