Database Structure: Foreign Key
Foreign Key
Section titled “Foreign Key”Foreign Key က table နှစ်ခုကြားမှာ relationship တစ်ခုကို ဖန်တီးပေးတဲ့ အဓိကကျတဲ့ field (column) တစ်ခုဖြစ်ပါတယ်။ Table နှစ်ခုကို ချိတ်ဆက်ချင်တယ်ဆိုရင် ပထမ table က primary key ကို ကူးယူပြီး ဒုတိယ table ထဲကို ထည့်သွင်းခြင်းဖြင့် ချိတ်ဆက်ရပါတယ်။ အဲဒီအခါ ပထမ table ထဲက primary key က ဒုတိယ table အတွက် Foreign Key ဖြစ်လာပါတယ်။
Foreign Key လို့ခေါ်ရတဲ့အကြောင်းရင်းကတော့ ဒုတိယ table မှာ သူ့ကိုယ်ပိုင် Primary Key ရှိနေပြီးသား ဖြစ်ပြီး ပထမ Table တစ်ခုဆီကနေ “ဧည့်သည်” (foreign) အဖြစ် လာရောက်ချိတ်ဆက်ပေးတဲ့ key ဖြစ်တဲ့အတွက် ဖြစ်ပါတယ်။
ဥပမာ -
Customers table
CustomerID (PK) | Name | |
|---|---|---|
1 | Alice | alice@gmail.com |
2 | Bob | bob@gmail.com |
CustomerIDက Customers table အတွက် primary key ဖြစ်ပါတယ်။
Orders table
| OrderID (PK) | OrderDate | CustomerID (FK) |
|---|---|---|
| 101 | 2024-06-01 | 1 |
| 102 | 2024-05-01 | 1 |
| 103 | 2024-07-01 | 2 |
OrderIDဟာ Orders table အတွက်Primary Keyဖြစ်ပါတယ်။ဒီနေရာမှာ
CustomerIDကတော့ Orders table မှာForeign Keyဖြစ်ပြီး၊ Customers table ထဲကCustomerID (PK)ကို ရည်ညွှန်းပါတယ်။ ဒီForeign Keyက အော်ဒါတစ်ခုစီကို ဘယ် customer က မှာယူခဲ့တယ်ဆိုတာကို ချိတ်ဆက်ပေးတာပဲ ဖြစ်ပါတယ်။
Customer တစ်ယောက်က အော်ဒါတစ်ခု မှာတဲ့အခါ အဲဒီအော်ဒါရဲ့အချက်အလက်တွေကို Orders table မှာ သိမ်းဆည်းပါတယ်။ ဒီအော်ဒါကို ဘယ် customer က မှာတယ်ဆိုတာသိဖို့ Customers table ထဲက customer ရဲ့ Primary Key ဖြစ်တဲ့ CustomerID ကို Orders table ထဲမှာ Foreign Key အနေဖြင့် ထည့်သွင်းပါတယ်။