Está en la página 1de 10

Joins

An SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each

SQL specifies four types of JOINs:


INNER OUTER OUTER LEFT OUTER RIGHT As a special case, a table (base table, view, or joined table) can JOIN to itself in a selfjoin.

In the following tables the DepartmentID column of the Department table (which can be designated as Department.DepartmentID) is the primary key, while Employee.DepartmentID is a foreign key.
LastName DepartmentI D Rafferty Jones Steinberg Robinson Smith John 31 33 33 34 34 NULL 31 33 34 35 Sales Engineering Clerical Marketing DepartmentID DepartmentName

Inner join
An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate

SELECT * FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID;

Equi-join
An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join

SELECT * FROM employee JOIN department ON employee.DepartmentID = department.DepartmentID;

SELECT * FROM employee INNER JOIN department USING (DepartmentID);

Natural join
A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equallynamed columns.

SELECT * FROM employee NATURAL JOIN department;

Cross join
CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each

row from the second table.


SELECT * FROM employee CROSS JOIN department; SELECT * FROM employee, department;

Self join
A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to compare values in a column with other values in the same column in the same table. One practical use for self-joins

SELECT p1.name, p1.sex, p2.name, p2.sex, p1.sp ecies FROM bird AS p1, bird AS p2 WHERE p1.species = p2.species

Outer Join
The syntax for performing an outer join in SQL is databasedependent. For example, in Oracle, we will place an "(+)" in the WHERE clause on the other side of the table for which we want to include all the rows. e.g

select eid,ename,dep.depid,dlocation from emp.dep where dep.depid=emp.depid(+)

También podría gustarte