Skip to content
GitHub

Database Structure: 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)NameEmail
1Alicealice@gmail.com
2Bobbob@gmail.com

CustomerID က Customers table အတွက် primary key ဖြစ်ပါတယ်။

Orders table

OrderID (PK)OrderDateCustomerID (FK)
1012024-06-011
1022024-05-011
1032024-07-012

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 အနေဖြင့် ထည့်သွင်းပါတယ်။