Thuta Learning
ရှာဖွေရန်
IntermediateData & Databasesbeginner

Subqueries နှင့် CTE

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Subqueries နှင့် CTE concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ SQL/command ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် အသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

Subquery က query အတွင်း query တစ်ခုဖြစ်ပြီး scalar value၊ row set သို့ existence စစ်ချက်အဖြစ်သုံးနိုင်ပါတယ်။ `EXISTS` က match ရှိမရှိသာလိုသည့်အခါ intent ရှင်းပြီး duplicate ပြဿနာမဖြစ်စေပါဘူး။ CTE က query ကိုအမည်ပေးထားသောအဆင့်များအဖြစ်ဖတ်ရလွယ်စေသော်လည်း performance ကို အလိုအလျောက်ကောင်းစေမည့် magic မဟုတ်ပါ။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Lesson အနည်းဆုံးတစ်ခုရှိသော published tutorial ကို `EXISTS` ဖြင့်ရွေးမယ်။ နောက် query မှာ enrollment count ကို CTE ဖြင့်တွက်ပြီး popular tutorial များကို catalog metadata နဲ့ချိတ်မယ်။

အတူတူ စမ်းရေးကြည့်မယ်

sql
SELECT t.tutorial_id, t.title
FROM app.tutorials t
WHERE t.is_published
  AND EXISTS (
    SELECT 1 FROM app.lessons l
    WHERE l.tutorial_id = t.tutorial_id
  );

WITH enrollment_totals AS (
  SELECT tutorial_id, count(*) AS enrollments
  FROM app.enrollments
  GROUP BY tutorial_id
)
SELECT t.title, e.enrollments
FROM enrollment_totals e
JOIN app.tutorials t USING (tutorial_id)
WHERE e.enrollments >= 10;
You should see
Lesson ပါသော tutorial နှင့် popular tutorial lists နှစ်မျိုးရမည်။

၅ မိနစ် စမ်းကြည့်

Progress row မရှိသေးသော enrollment များကို `NOT EXISTS` ဖြင့်ရှာပါ။

သတိလေးတစ်ချက်

`NOT IN` subquery ထဲ NULL ပါနိုင်ရင် မျှော်လင့်မထားသော result ရနိုင်ပါတယ်။ Anti-join အတွက် `NOT EXISTS` ကိုစဉ်းစားပါ။

PostgreSQL — WITH QueriesPostgreSQL Global Development Group

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • `NOT IN` subquery ထဲ NULL ပါနိုင်ရင် မျှော်လင့်မထားသော result ရနိုင်ပါတယ်။ Anti-join အတွက် `NOT EXISTS` ကိုစဉ်းစားပါ။
  • နမူနာ code ကို production data ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test database နှင့် recoverable backup ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

Progress row မရှိသေးသော enrollment များကို `NOT EXISTS` ဖြင့်ရှာပါ။

You'll know it worked when: Lesson ပါသော tutorial နှင့် popular tutorial lists နှစ်မျိုးရမည်။

Subqueries နှင့် CTE | Thuta Learning