Foreign Key
Foreign Key ဆိုတာ ဘာလဲ?
Section titled “Foreign Key ဆိုတာ ဘာလဲ?”Foreign Key ဆိုတာ Table နှစ်ခုကြားမှာ ဆက်စပ်မှု (Relational Relationship) တည်ဆောက်ဖို့နဲ့ Data Integrity ထိန်းသိမ်းဖို့ အသုံးပြုတဲ့ Field (သို့မဟုတ် Field ပေါင်းစပ်မှု) ဖြစ်ပါတယ်။
လွယ်လွယ်ပြောရရင်: Parent Table တစ်ခုရဲ့ Primary Key ကို Child Table ထဲမှာ Reference အနေနဲ့ ယူသုံးထားတဲ့ Field ကို Child Table ရဲ့ Foreign Key လို့ ခေါ်ဆိုပါတယ်။
Table ချိတ်ဆက်ပုံ ဇယား
Section titled “Table ချိတ်ဆက်ပုံ ဇယား”employees Table (Child)
| id (PK) | name | department_id (FK) |
|---|---|---|
| 1 | Alice | 101 |
| 2 | Bob | 102 |
departments Table (Parent)
| department_id (PK) | department_name |
|---|---|
| 101 | HR |
| 102 | IT |
ဒီလို Foreign Key နဲ့ ချိတ်ဆက်လိုက်တဲ့အတွက် “Alice ရဲ့ ဌာနဟာ HR (101) ဖြစ်တယ်” ဆိုတာကို Query ပြုလုပ်ပြီး ရယူနိုင်သွားပါတယ်။
Foreign Key ရဲ့ အဓိက အကျိုးကျေးဇူးများ
Section titled “Foreign Key ရဲ့ အဓိက အကျိုးကျေးဇူးများ”- Referential Integrity (အချက်အလက် ကိုက်ညီ မှန်ကန်မှု): Foreign Key တည်ရှိနေတဲ့အတွက် Parent Table (
departments) ထဲမှာ မရှိသေးတဲ့ ID (ဥပမာ -999) ကို Child Table (employees) ထဲမှာ သွားရောက် ရေးသွင်းလို့ မရအောင် Database က အလိုအလျောက် တားဆီးပေးပါတယ်။ - Cascading Operations: Parent Table မှ Data ဖျက်ပစ်ပါက သို့မဟုတ် ပြင်ဆင်ပါက Child Table ရှိ Data များကိုလည်း
ON DELETE CASCADEသို့မဟုတ်ON UPDATE CASCADEစည်းမျဉ်းများဖြင့် အလိုအလျောက် လိုက်ပါ ပြုပြင်ပေးနိုင်ပါတယ်။