MySQL left join query
- Monday, July 26, 2010, 8:21
- Database, MySQL, SQL basics
- Add a comment
|
|
This is the one of method to joining two tables. It returns all rows from the left table, even if there are no matches in the right table
Syntax of the left join query:
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Here is the two table with some data.
| Table (names) | Table (places) | ||||||||||||||||
|
|
We want join these two tables by using left join.
Here is the left join sql query to display this and below that the output is listed.
SELECT names.id, names. f_name, places.n_place FROM names left join places on names.id = places.id
The result will show like this:
| id | f_name | place |
| 1 | pappy | palakkad |
| 2 | Regina | calicut |
| 3 | pooja | kannur |
We named the above result table as Customer, then again we can join table Customer with the below mentioned table Order.
Table Customer
| id | f_name | place |
| 1 | pappy | palakkad |
| 2 | Regina | calicut |
| 3 | pooja | kannur |
Table Orders
| o_id | orderno | id |
| 1 | 8644 | 3 |
| 2 | 4468 | 3 |
| 3 | 1238 | 1 |
| 4 | 2738 | 1 |
| 5 | 3648 | 10 |
The left join query forĀ joining these two tables is shown below:
SELECT Customer.f_name, Customer.place, Orders.orderno
FROM Customer
LEFT JOIN Orders
ON Customer.id=Orders.id
ORDER BY Customer.f_name
The result of the above query display like below.
| f_name | place | orderno |
| pappy | palakkad | 1238 |
| pappy | palakkad | 2738 |
| pooja | kannur | 8644 |
| pooja | kannur | 4468 |
| Regina | calicut |


