Skip to content

資料庫 ER Model(一): Entity 與 Attribute

davidlei

Entity

entity 是 RDBMS 中實際的資料實體,可以用程式的概念來理解:定義好 struct 之後,一定會在某個地方建立一個實體,裡面的欄位根據 struct field type 存放資料。

type student struct {
    name string
    age int
}

func main() {
    studentA := student{"david", "20"}
}

studentA 就可以視為一個 entity,是擁有真實資料的實體。

Attribute

attribute 描述 entity 的屬性,以上面 student 為例,nameage 都算是 attribute。

在資料庫中,attribute 大致可以分成 SimpleCompositeMulti-valued 三種類型。

Simple

Simple attribute 是無法再進一步分割的欄位,對應到程式語言中的基本資料型別,例如 studentage 就是單純的 int

Composite

Composite attribute 是由多個不同部分組合而成的概念,例如外國人的姓名可能包含 FirstNameMiddleNameLastName

type name struct {
    FirstName string
    MiddleName string
    LastName string
}

type student struct {
    studentName name
    studentAge int
}

此時 name 代表三個 string 的組合,就可以視為一個 Composite attribute。

Multi-valued

Multi-valued attribute 代表單個 attribute 內可以有多個值。課堂上舉的例子是車子的顏色:一台車不同部位可能有不同顏色,如果資料庫需要描述外觀顏色,就需要用到 Multi-valued attribute。雖然存在這個概念,但實際設計時通常會將它拆解,拆法之後會再介紹。

Multi-valuedComposite 可以同時出現,兩者並不衝突。

Key Attribute

key attribute 用來唯一識別一個 entity。

key attribute 沒有特別的形式限制,也可以是 Composite attribute。某些情況下需要組合多個 attribute,才能唯一識別一個 entity。

Key attribute 跟 Primary key 的差別是什麼?

Entity Set(Entity collection)

代表當下所有 entity 的集合。

ER diagrams

課本以 CAR 作為 ER diagrams 的範例,這裡我試著用 Go 語言的宣告來理解:

// Composite 
type registration struct {
    State string
    Number int
}

type Car struct {
    VehicleID string
    Registration registration
    Year int
    Color []color 
    Make string
    Model string
}

其中 Registration 是 Composite attribute,Color 是 Multi-valued attribute,畫出來的圖如下:

Vehicle_idRegistration 都可以作為 Key attribute,所以有加上底線。Color 的雙框則代表 Multi-valued attribute。

Example Company DB

Company DB 是課本最常用的範例,目前第三章的初步設計如下,之後會隨課程進度持續優化。

Relationship

上面的初步設計少了 relationship 的部分,光看那張圖無法得知各個 entity type 之間的關係。

relationship 只能描述 entity type 與 entity type 之間的關係,不能用在 attribute 之間。

relationship 沒有限定只能連結兩個 entity type,多個 entity type 之間也可以建立 relationship,但大多數設計還是以兩個不同的 entity type 之間為主。

同一組 entity type 之間可能存在多種 relationship type,遇到這種情況要分別畫出來,不能因為數學上看起來重複就省略。

每個 employee 都為 department 工作,WORKS_FOR 的關係

應該也有一個 employee 是主管,負責管理 department,MANAGES 的關係

這種情況雖然兩者涉及的 entity type 一樣,但是因為關係的意義不同,要分成兩個 relationship

Relationship degree

degree 代表這個 relationship 關聯了幾個 entity type。若關聯了兩個 entity type,則稱為 binary relationship,此時 degree = 2。

example

回到上面 Company DB 的示意圖,每個 Employee 都應該隸屬於某個 Department,所以這兩個 entity type 之間存在 relationship,且這是一對一的關係。

另外,每個 Employee 可能負責多個 Project,所以 Employee 和 Project 之間也存在 relationship,且是多對多的關係。

Relationship Set

上圖 r1 ~ r7 總共有七條 relationship,這些實際存在的 relationship 的集合統稱為 Relationship Set。

Relationship type

WORKS_ON 這樣的關係分類本身稱為 Relationship type。

Edit this post
Previous
Concurrency vs Parallelism 淺談兩者區別以及名詞介紹
Next
leetcode 1022. Sum of Root To Leaf Binary Numbers [Easy]