Chapter 8

Database Keys and Relationship

Database Keys

Database Normalization မလုပ်ခင်မှာ Database မှာ အသုံးပြုသည့် Key အခေါ်အဝေါ်တွေကို သိဖို့လိုပါတယ်။ ပထမဆုံး အောက်က Table ကို လေ့လာကြည့်ပါ။

Student Table

student_id name phone age
1 Ba Oo 09976554398 18
2 Aye Maung 09796553118 22
3 Pyone Cho 09501231421 22
4 Ko Oo 0951412321 19

Super Key

Super Key ကတော့ column တစ်ခု သို့မဟုတ် တစ်ခု ထက်မက လည်း ဖြစ်နိုင်ပါတယ်။ Unique ဖြစ်သည့် column အမျိုးအစားပါ။

student_id , student_id + name , phone စတာတွေက key ပါပဲ။ age ကတော့ student ကို ကိုယ်စားမပြုနိုင်ပါဘူး။ student_id က student တစ်ယောက်တည်းကို ကိုယ်စားပြုနိုင်တယ်။ name က duplicate ဖြစ်နိုင်တယ်။ ဒါပေမယ့် student_id + name ဆိုပြီး column ၂ ခု ပေါင်းရင် student ကို ကိုယ်စားပြုနိုင်ပါတယ်။ phone လည်း အတူတူပါပဲ။

key တွေ အကုန်လုံးက super key လို့ ခေါ်ပါတယ်။

Candidate Key

Student table မှာ ဆိုရင်တော့ student_id နှင့် phone က candidate key တွေဖြစ်ပါတယ်။

Primary Key

Primary key ကိုတော့ candidate key ထဲက ရွေးချယ်ပါတယ်။ student_id နှင့် phone မှာ ဆိုရင်တော့ Primary key အနေနဲ့က student_id ထားဖို့ သင့်တော်ပါတယ်။ phone number က ကျောင်းသားက ပြောင်းနိုင်ပေမယ့် student_id ကတော့ မပြောင်းပါဘူး။​ နောက်ပြီး primary key က database ကနေ auto increment လုပ်သွားပါတယ်။

Foreign Key

Foreign key ကတော့ table တစ်ခု နဲ့ တစ်ခု relationship အနေနဲ့ အသုံးပြုပါတယ်။

Foriegn Key ကို နားလည် အောင် နောက်ထပ် Branch table ထပ်ဖြည့်ပါမယ်။

Branch Table

branch_code branch_name HOD
CS Computer Science Daw Swe Swe
CT Computer Technology U Thein Maung

အခု Student Table မှာ branch ထပ်ဖြည့်ပါမယ်။\

|student_id | name | phone | age | branch_code |
| --------- | ---- | ---- | ---- |
| 1 | Ba Oo | 09976554398 | 18 | CS |
| 2 | Aye Maung | 09796553118 | 22 | CS |
| 3 | Pyone Cho | 09501231421 | 22 | CT |
| 4 | Ko Oo | 0951412321 | 19 | CT |

အခုဆိုရင် branch_code က student table မှာ Foreign Key အနေဖြင့် ရှိပါတယ်။

Student Table မှာ Branch Table မှာ မရှိသည့် branch code ကို ထည့်ခွင့်မရှိပါဘူး။ Branch table မှာလည်း branch_code ကို ဖျက်လို့မရပါဘူး။ ဖျက်သည့် အခါမှာတော့ student table မှာ reference ရှိနေသည့် အတွက် error တက်လာပါမယ်။ Student table မှာ ဖျက်ချင်သည့် branch code ကို ပြင်ပြီးမှ ဖျက်လို့ရပါမယ်။

Composite Key

Key ဟာ column တစ်ခု ထက် ပိုပါနေသည့် key ကို Composite လို့ ခေါ်ပါတယ်။ Student table မှာ student_id + name နဲ့ composite key ဖြစ်ပါတယ်။

Compound Key

Composite Key ထဲက column တစ်ခုဟာ foreign key ဖြစ်ခဲ့ရင် compound key လို့ သတ်မှတ်ပါတယ်။

Student table မှာ ဆိုရင် student_id + branch_code ဟာ Compound key ဖြစ်ပါတယ်။

Surrogate Key

Surrogate Key ဆိုတာက primary key အနေနဲ့ အသုံးပြုထားပြီး အဓိက index နဲ့ search အတွက် အသုံးပြုဖို့ အတွက် ဖန်တီးထားသည့် key ပါ။ MySQL မှာဆိုရင်တော့ auto_increment အနေနဲ့ အသုံးပြုပါတယ်။ သီးသန့် သတ်မှတ်ထားတာ မဟုတ် ပဲ row တစ်ကြောင်းထည့်တိုင်း အလိုလို 1 တိုးသွားပါတယ်။

ဥပမာ

surrogate_key branch_code branch_name HOD
1 CS Computer Science Daw Swe Swe
2 CT Computer Technology U Thein Maung