Mysql Join
Mysql Join
Syntax:
SELECT *FROM `members`AS A LEFT JOIN `movies` AS B ON B.`id` =
A.`movie_id`
UNION
SELECT *FROM `members`AS A RIGHT JOIN `movies` AS B ON B.`id` =
A.`movie_id`
LEFT JOIN
• Assume now you want to get titles of all movies together with names of
members who have rented them. It is clear that some movies have not
being rented by any one. We can simply use LEFT JOIN for the purpose.
• The LEFT JOIN returns all the rows from the table on the left even if no
matching rows have been found in the table on the right.
• Example:
SELECT A.`title` , B.`first_name` , B.`last_name` FROM `movies` AS A LEFT
JOIN `members` AS B ON B.`movie_id` = A.`id`
RIGHT JOIN
• The RIGHT JOIN returns all the columns from the table on the right even if
no matching rows have been found in the table on the left.
• Where no matches have been found in the table on the left, NULL is
returned.
• Example:
SELECT A.`first_name` , A.`last_name`, B.`title` FROM `members` AS A RIGHT JOIN `movies`
AS B ON B.`id` = A.`movie_id`
Why should we use joins?