Understanding JOINS
Understanding JOINS
INTRODUCTION TO JOINS
● The cross join is useful for generating planning data but in same time,
due to the number of rows that will be returned, you should be careful
when using it. Following diagrams shows the product of cross join
SELF JOIN
● A self join in MySQL is when a table is joined with itself. This means
that the table is treated as if it were two separate tables, allowing you
to compare rows within the same table. Self joins are typically used
when you need to compare rows within a single table, such as when
you want to find related records or hierarchical data.
● For example, suppose you have a table called "employees" with
columns like "employee_id" and "manager_id", where the
"manager_id" refers to the "employee_id" of another employee who is
the manager. You could use a self join to retrieve information about
both the employee and their manager in a single query.
SELF JOIN
● Following is the query that would extract the information about the
employee and his manager
SELECT e.employee_id,
e.employee_name,
m.employee_id AS manager_id,
m.employee_name AS manager_name
FROM employees e
JOIN employees m ON e.manager_id = m.employee_id;
● In this query, the "employees" table is aliased as both "e" and "m",
allowing us to compare each employee's "manager_id" with another
employee's "employee_id" within the same table.
SELF JOIN
● Following diagram depicts the idea behind the self join where the table
has foreign key reference to itself and is being joined to itself
JOIN CONDITIONS
● In MySQL, join conditions are typically applied in the ON clause or the USING
clause of a join statement as we have show previously
● However, although it is not recommended, we can add the join conditions in
the WHERE clause as shown in the example below
SELECT *
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name
WHERE table1.some_column = table2.some_column;
● Placing join conditions in the ON clause clearly indicates that these
conditions are part of the join operation, making the query more
understandable. It also helps to separate join conditions from filtering
conditions, which are typically specified in the WHERE clause.
JOIN CONDITIONS CONT.
● Also it is important to note that we can add multiple condition on the
ON clause if needed. In most cases we will only add the
primary-foreign key constraint but in some occasions we also have to
specify additional conditions in our ON clause as shown in the
example below
SELECT *
FROM customers c
JOIN orders o ON
c.customerNumber = o.customerNumber AND
o.orderDate > 20030101 AND o.orderDate < 20030110;
Thank you