簡體   English   中英

自動增量列應為主鍵嗎?

[英]Should the auto increment column be the primary key?

我對如何分配主鍵感到困惑。

例如,假設我有以下兩個表:

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_iduser_id 請解釋。

謝謝!

Posts表的主鍵也應該是自動增量值post_id,因為它是唯一標識每個帖子的唯一內容,因為每個帖子都有一個與其他任何人都不一樣的ID。 user_id並不總是唯一的,因為同一用戶可能有多個帖子(據我所知),因此它不能唯一地標識這些帖子。 如果您需要在兩個表之間關聯信息,則始終可以對兩個表的user_id進行聯接,但是要用主鍵標識事物,post_id將是您的最佳選擇。

當然,您有以下場景:

  • 用戶可以發布多個帖子。
  • 邏輯上,一個用戶只能發布一個帖子。

因此,您正在處理一對多模型。

一旦您了解了這些內容,您就可以猜測users的主鍵必須在posts顯示為外鍵。 這顯然是您已經完成的。

現在, post_id就足夠了,因為posts的主鍵取決於您擁有的整個實體關系模型(您擁有多少個其他實體以及它們之間的關系是什么)。

但是,對於此特定方案,您不需要將外鍵user_id組合為posts主鍵的一部分。

注意:在實現表時,請將auto_increment的約束添加到user_idpost_idnot null

讓我們總結一下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)

當然,它應該是user_id,因為當您使用ORM時,它將通過正確的鍵名自動映射表。您可以在這里參考ORM: 好的PHP ORM庫?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM