Joins 1) Inner Joins - : I. Equi-Join
Joins 1) Inner Joins - : I. Equi-Join
Joins
1) Inner joins –
An INNER JOIN combines the records from two tables using comparison operators in a condition.
An INNER JOIN is a CROSS JOIN with some result rows removed by a condition in the query.
There are four type of INNER JOINs as below
I. EQUI-JOIN:
We can use our inner join with the = operator to match up the foreign key in boys to the primary
key in toys.
Example -
--Inner join
SELECT
BOYS.BOY,
TOYS.TOY
FROM
BOYS
INNER JOIN TOYS ON BOYS.TOY_ID = TOYS.TOY_ID;
II. NON-EQUIJOIN:
The non-equijoin returns any rows that are not equal. We can see exactly which toys each boy
doesn’t have (which could be useful around their birthdays).
SELECT
BOYS.BOY,
TOYS.TOY
FROM
BOYS
INNER JOIN TOYS ON BOYS.TOY_ID <> TOYS.TOY_ID
ORDER BY BOYS.BOY;
Ex -
IF DOSRUBRIQUE have 8 records and DOSACTADRESSE have 8 records , it will give 8*8=64
records for below query –
--Cross join
SELECT
B.BOY,
T.TOY
FROM
BOYS AS B
CROSS JOIN TOYS AS T;
--CROSS join
SELECT
BOYS.BOY,
TOYS.TOY
FROM
BOYS CROSS JOIN TOYS
WHERE BOYS.TOYID = TOYS.TOYID;
--Natural Join
SELECT
BOYS.BOY,
TOYS.TOY
FROM
BOYS
NATURAL JOIN TOYS;
2) OUTER JOIN:
By comparison with inner join, outer joins have more to do with the relationship between two tables
than the joins you’ve seen so far. It’s about left and right.
Difference: The difference is that an outer join gives you a row whether there’s a match with the
other table or not. And a NULL value tells you no match exists.
A LEFT OUTER JOIN takes all the rows in the left table and matches them to rows in the RIGHT
table. It’s useful when the left table and the right table have a one-to-many relationship. The
keyword ON is mandatory.
In a LEFT OUTER JOIN, the table that comes after FROM and BEFORE the join is the LEFT table,
and the table that comes AFTER the join is the RIGHT table.
SELECT
G.GIRL,
T.TOY
FROM
GIRLS G
INNER JOIN TOYS T ON G.TOY_ID = T.TOY_ID;
By using LEFT OUTER JOIN:
SELECT
G.GIRL,
T.TOY
FROM
GIRLS G
LEFT OUTER JOIN TOYS T ON G.TOY_ID = T.TOY_ID;
Still it gives the same result. It is because there are all matches in the RIGHT table with respect
to left table. If RIGHT table has no value that corresponds to LEFT table then a NULL value will
be displayed in the result for RIGHT table columns.
SELECT
G.GIRL,
T.TOY
FROM
TOYS T
LEFT OUTER JOIN GIRLS G ON G.TOY_ID = T.TOY_ID;
Outer joins and multiple matches:
Result:
VI. The right outer join:
The right outer join is exactly the same thing as the left outer join, except it compares the
right table to the left one. The two queries below give you precisely the same results: The
right outer join evaluates the right table against the left table.
SELECT
G.GIRL,
T.TOY
FROM
TOYS T
RIGHT OUTER JOIN GIRLS G ON G.TOY_ID = T.TOY_ID;
Equivalent to ->
SELECT
G.GIRL,
T.TOY
FROM
GIRLS G
LEFT OUTER JOIN TOYS T ON G.TOY_ID = T.TOY_ID;