【问题标题】:Should the auto increment column be the primary key?自增列应该是主键吗?
【发布时间】:2022-03-18 22:48:31
【问题描述】:

我对如何分配主键感到困惑。

例如,假设我有这两个表:

users 表,其中user_id 是唯一的:

+---------+----------+--------------+
| user_id | username |   password   |
+---------+----------+--------------+
|       1 | hello    | somepassword |
|       2 | world    | another      |
|       3 | stack    | overflow     |
+---------+----------+--------------+

posts 表,其中post_id 是唯一的:

+---------+---------+--------------+
| post_id | user_id |   content    |
+---------+---------+--------------+
|       1 |       1 | Hello World! |
|       2 |       1 | Another.     |
|       3 |       3 | Number 3.    |
|       4 |       2 | Stack.       |
|       5 |       1 | Overflow.    |
+---------+---------+--------------+

显然 users 表的主键应该是user_id,但是 posts 表中的主键应该是什么? post_id 还是 user_id?请解释一下。

【问题讨论】:

  • 这是你的愿望.. 但是由于 user_id 不能是主要的,所以除了将 post_id 设为主要之外别无选择

标签: mysql sql


【解决方案1】:

Posts 表的主键也应该是自动递增值 post_id,因为它是唯一标识每个帖子的唯一内容,因为每个帖子都有一个不同的 id。 user_id 并不总是唯一的,因为同一个用户可能有多个帖子(据我所知),所以它不能唯一地识别帖子。如果您需要在表之间关联信息,您始终可以对两个表的 user_id 进行连接,但是要使用主键识别事物,post_id 将是您的最佳选择。

【讨论】:

  • 好的,关于这种情况,为了简单起见,让我们说 posts 表中的user_id 也是唯一的,但不是自动递增的。那么主键应该是哪个?
  • 理论上,如果它们始终是唯一的,您可以使用其中任何一个,但约定可能仍然使用 post_id。但实际上,一个用户应该可以发布多个帖子,因此 user_id 很可能不会是唯一的。
【解决方案2】:

当然,你有这样的场景:

  • 一个用户可以发布多个帖子。
  • 一个帖子在逻辑上只能由一个用户发布。

因此,您正在处理One-To-Many 模型。

一旦这些事情你都清楚了,你就可以猜到users的主键一定是作为外键出现在posts中的。这显然是你已经做过的。

现在,post_id 是否足够,因为 posts 的主键取决于您拥有的整个实体关系模型(您拥有多少其他实体以及它们之间的关系)。

但是,对于此特定场景,您不需要将外键 user_id 组合为 posts 的主键的一部分。

注意:当你实现你的表时,请将auto_incrementnot null的约束添加到user_idpost_id

让我们用 SQL 总结一下所有这些混乱:

users:

mysql> create table users (user_id int(2) unique  auto_increment not null, username varchar(15) not null, password varchar(20) not null, primary key(user_id));Query OK, 0 rows affected (0.33 sec)

posts

mysql> create table posts(post_id int(2) unique auto_increment not null, user_id int(2) not null, content varchar(50) not null, foreign key(user_id) references users(user_id), primary key(post_id));
Query OK, 0 rows affected (0.26 sec)

【讨论】:

    【解决方案3】:

    当然应该是 user_id,因为当你使用 ORM 时,它会根据键的正确命名自动映射表 您可以在这里参考 ORM:Good PHP ORM Library?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2011-11-12
      • 1970-01-01
      • 2018-06-05
      • 2011-07-21
      • 2015-06-30
      • 1970-01-01
      相关资源
      最近更新 更多