Overview
TheLEFT JOINreturns all matching records from the left table combined with the right table. Even if there are no matching records in the right table, the LEFT JOIN will still return a row in the result, but with NULL in each column from the right table.
LEFT JOIN is also known as LEFT OUTER JOIN.Syntax
We support table aliasing used in the
LEFT JOIN clause.a) Basic Syntax
SELECT column_1, column_2...defines the columns from both tables where we want the data to be selected.FROM table_1defines the left table as the main table in the FORM clause.RIGHT JOIN table_2defines the right table as the table the main table joins.ON table_1.matching_field = table2.matching_fieldsets the join condition after the ON keyword with the matching field between the two tables.
b) Syntax with an Alias
You can use an alias to refer to the table’s name. The results will stay the same. It only helps to write the query easier.Example
item table1) Based on the above tables, we can write a
LEFT JOIN query as follows:
- The item = left table, and the invoice = right table.
- Then it combines the values from the item table using the item_no and matches the records using the item column of each row from the invoice table.
-
If the records are equal, a new row will be created with
item_no,item_name, andsold_qty,sold_pricecolumns as defined in theSELECTclause. -
ELSE it will create a new row with a
NULLvalue from the right table (invoice).
- The result matches the total item stored in the item table: 4 items.
- The result will display all the item’s data from the left table (item table), even if there is 1 item that hasn’t been sold.
- The item id:
111matches the itembutterand has been sold for 3pcs/9000. - The item id:
113matches the itemteabut has never been sold. Thus the sold_qty & sold_price columns are filled with: null. - The item id:
116matches the itemBreadand has been sold three times, for 6pcs/3000, 2pcs/10000, and 1pc/5000. - The item id:
119matches the itemCoffeeand has been sold two times, for 5pcs/20000 and 4pcs/16000.
An item can have zero or many invoices. An invoice belongs to zero or one item.
LEFT JOIN:
