簡體   English   中英

有沒有辦法在 PostgreSQL 數據庫中有效地生成復合鍵?

[英]Is there a way to generate composite key efficiently in a PostgreSQL database?

假設我有一個以 id 作為主鍵的學生表,其中包含所有學生的信息。

id | name
---+------
 1 | aaron
 2 | bob

此外,還有一個表格,其中 id 和 tid 形成了一個復合鍵,其中保存了每個測試的分數。

id | tid | score 
---| --- | -----  

注意:不同的學生有不同的測試,不同的數字,沒有相關性。 tid 根本不代表特定的測試,而是代表學生的測試序列號。 id=1 and id=2,如果tid=1,不代表是同一個測試。

生成 tid 有兩種方式,一種是全局唯一的,每插入一條記錄就加 1,例如

id | tid | score 
-- | --- | -----  
 1 |  1  | 99
 1 |  2  | 98
 2 |  3  | 97
 2 |  4  | 96

另一個在特定的id內是唯一的,不同的id可以有相同的tid取值,例如

id | tid | score 
-- | --- | -----  
 1 |  1  | 99
 1 |  2  | 98
 2 |  1  | 97
 2 |  2  | 96  

對於后者,有沒有更高效、更簡單的實現方式呢?

create table student(id integer PRIMARY KEY, name varchar);
create table test(tid integer PRIMARY KEY, name varchar, test_date date);
create table test_score(sid integer, tid integer references test, score integer, PRIMARY KEY(sid, tid);

正確的設計是選項 2,因為 tid 應該引用(即作為外鍵)進行的測試(即問題的集合); 每次學生參加考試時都不會創建一個新的考試實例——參加給定考試的所有學生都參加相同的考試(即回答相同的問題)。

如果學生可以多次參加同一測試,請添加日期列(如果同一天可能進行多次嘗試,則添加時間戳)以區分同一測試中重復嘗試的結果。

暫無
暫無

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

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