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

- 收集到 Requirements 最難,很難提出"精準"的需求
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 的例子,name, age 都可以當作 attribute。
在資料庫內 attribute 分成很多不同類型,大致可以分成 Simple, Composite, Multi-valued。
Simple
Simple attribute 通常指那些無法繼續再分割的 field,對應到程式語言可以理解成基本的 data type,像是 student 的 age 就是單純的 int。
Composite
Composite attribute 是由多個不同的部份組成一起的概念,像是外國的名字可能有 FirstNAme, MiddleName, LastName 等等
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 內有多個 value,像是上課舉例是用車子的顏色,一個車子不可能從頭到尾只有一個顏色,不同區域可能會有不同的顏色,這時候如果我們資料庫需要描述這個車子的外觀顏色,就會用到 Multi-valued attribute,雖然有 Multi-valued attribute,但實際設計上通常都會把它拆開,實際怎麼分解的之後會再介紹。
Multi-valued 跟 Composite 是有可能同時出現的,彼此之間不衝突。
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_id 跟 Registration 都可以當作 Key attribute,所以有加上底線。
Color 的雙框代表 Multi-valued attribute。
Example Company DB
Company DB 是課本最常用的例子,目前到第三章的初步設計如下,之後會根據課程進度去逐漸優化。
- Department
- name
- number
- employees
- start date of the department manager
- locations
- projects
- Project
- department
- unique name
- unique number
- single location
- Employee
- SSN
- name
- address
- sex
- birthdate
- salary

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 relationships,所以 degree=2。
example
回到上面 Company DB 的示意圖,我們可以每個 Employee 都應該隸屬於某個 Department,所以這兩個 entity type 之間會有 relationship,這個 relationship 是一對一的關係。

然後每個 Employee 可能會負責多個 Project,所以 Employee 跟 Project 之間也可以畫出一個 relationship,這個 relationship 是屬於多對多的關係。

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