自动增量列应该是主键吗?

时间:2014-11-22 07:03:40

标签: mysql sql mysqli

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

例如,我们说我有这两个表:

用户 user_id唯一的表格

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

发布post_id唯一的表:

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

显然,对于用户表,主键应为user_id,但主键应位于帖子表中? post_iduser_id?请解释一下。

谢谢!

3 个答案:

答案 0 :(得分:0)

Posts表的主键也应该是自动增量值post_id,因为它是唯一唯一标识每个帖子的内容,因为每个帖子都有一个与其他帖子不同的ID。 user_id永远不会是唯一的,因为同一个用户可能有多个帖子(据我所知),因此它不能唯一地标识帖子。如果您需要在表之间关联信息,您可以随时从两个表中对user_id进行连接,但是为了使用主键识别事物,post_id将是您最好的选择。

答案 1 :(得分:0)

当然,你有这个场景:

  • 用户可以发布多个帖子。
  • 只能由一位用户以逻辑方式发布帖子。

因此,您正在处理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)

答案 2 :(得分:-1)

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