27/06/2024
මොනාද මේ SQL JOINS කියන්නේ?
SQL JOIN කියන්නෙත් SELECT, FROM, UPDATE, DELETE, WHERE වගේම SQL Clause එකක්. අපි මේ SQL JOIN clause එක use කරන්නෙ SQL tables දෙකක් හෝ කිහිපයක් specific column එකකින් combine කරලා data retrieve කරගන්න.
JOINS වර්ග 4ක් තියෙනවා. INNER JOIN, LEFT JOIN, RIGHT JOIN, OUTER JOIN තමා ඒ 4. අපි හැමෝම දන්නවා table එකකින් data retrieve කරන්න අපි use කරන්නෙ SELECT column_names FROM table_name කියන Query එක. එතකොට මේ From ට පස්සෙ අපි table_name එකක් දානවනෙ, මේ table එකට තමා අපි තව table එකක් JOIN keyword එකෙන් combine කරන්නෙ.
eg:
SELECT empName, depName FROM employees e
INNER JOIN departments d ON e.depID = d.depID
මුලින්ම අපි බලමු INNER JOIN කියන්නෙ මොකද්ද කියලා. INNER JOIN එකෙන් වෙන්නෙ tables දෙකේම matching records තියෙනවා නම් ඒක return කරන එක. මොනාද මේ matching records කියන්නෙ? දැන් අපි හිතමු orders table එකකුයි customers table එකකුයි තියෙනවා කියලා. Orders table එකේ primary key eka orderID සහ customers table එකේ primary key එක customerID. Order table එකේ foreign key එකක් විදියට customerID column එක තියෙනවා. Order table එකේ record එකක customerID එකත් එක්ක ගැලපෙන, customers table එකේ record එකක් තියෙනවා කියන්නෙ matching record එකක්. එතකොට මේ order table එකේ record එකක customerID එකක් තිබුනේ නෑ හරි, මේ order table එකේ තියෙන customerID එකකට අදාල record එකක් customer table එකේ තිබුනෙ නැත්තම් ඒවා unmatching records.
දැන් අපි බලමු LEFT JOIN ගැන. LEFT JOIN එකෙන් කරන්නෙ left table එකත් එක්ක right table එකේ මැච් වෙන records තියෙනවා නම් ඒ ටික සහ left table එකේ ඉතුරු records ඔක්කොමයි return කරන එක. අපි හැම වෙලේම මතක තියාගන්න ඕනේ මේකෙදි right table එකේ තියෙන records, left table එකට match උනත් නැතත්, Left table එකේ ඔක්කොම records මේකෙන් return කරනවා. අපි කොහොමද left table එක මොකද්ද right table එක මොකද්ද කියලා හොයාගන්නෙ? ක්රමේ තමයි FROM keyword එකත් එක්ක හැමවෙලේම එන්නෙ left table එක. FROM එකත් එක්ක left table එක දැම්මට පස්සෙ අපි JOIN keyword එකත් එක්ක දාන්නෙ Right table එක. එතකොට අපේ කලින් example එකට LEFT JOIN use කරලා left table එක විදිය්ට customers table එක දැම්මොත් ඔක්කොම customers ලා return කරනවා! Orders දාපු අයයි නැති අයයි. RIGHT JOIN එකේ වෙන්නෙ ඕකෙ opposite, right table එකේ left table එකත් එක්ක match වෙන records උයි right table ඉතුරු ඔක්කොම records return කරන එක.
FULL OUTER JOIN එක තමා අපේ අනිත් JOIN වර්ගෙ, මේ JOIN එකෙන් අපිට right table එකෙයි left table එකයි එකිනෙකට match වෙන records උයි, left table එකයි right table එකයි එකිනෙකට match නොවෙන records උයි සේරම return කරනවා, ඒ කියන්නෙ orders table එකේයි customers table එකෙයි match වෙන records, customers table එකේ ඉතුරු ඔක්කොම records සහ orders table ඉතුරු ඔක්කොම records return කරනවා.
තවත් මේ වගේ දේවල් දැනගන්න මේ Post එකට Like කරලා අපේ Page එක Follow කරන්න CeyCode 😊