MySQL INNER JOIN

My SQL Inner Join Example

My SQL Inner Join Example

This Article shows you how to write inner joins with the INNER JOIN keywords.

Please note: In MySQL the join keywords JOIN and CROSS JOIN are synonymous with INNER JOIN which means: All example statements found in this article work fine when you use JOIN or CROSS JOIN instead of INNER JOIN.

Syntax
Here are syntax examples for the impatient. A join condition can be specified in two different ways. Take a look at the following join examples:

— inner join with USING clause

SELECT *
FROM a INNER JOIN b
USING()

— inner join with ON clause

SELECT *
FROM a INNER JOIN b
ON a. = b.

Now we should take a closer look at inner joins and what they really do.

Basics

The most common join operation MySQL supports is an inner join. It identifies and combines only matching rows which are stored in two related tables. A join condition which indicates how the tables are related, is added with the keywords ON or USING :

ON is used when the relationship column has a different name
USING is used when the relationship column has the same name in both tables
Take a look at the examples:

— INNER JOIN with ON clause
SELECT *
FROM tableA a
INNER JOIN tableB b
ON  a.someColumn = b.otherColumn

— INNER JOIN with USING clause
SELECT *
FROM tableA a
INNER JOIN tableB b
USING(columnName)

Inner Join vs Cross Join

In MySQL, the keywords CROSS JOIN and INNER JOIN are synonymous. ANSI SQL defines a CROSS JOIN as a join without a condition which builds the Cartesian product of two tables. In that case, MySQL combines every row in the left table with every row in the right table and returns the result set.

— inner join without a condition: cross join
SELECT *
FROM CROSS JOIN

When you have to build the Cartesian product of two tables, use the CROSS JOIN keywords to indicate your intensions. It makes it easy to read your statement and of course, keeps your code more portable.

Inner Join vs Outer Join
The major dhifference between outer joins and inner joins is: an outer join is able to identify rows that were not matched by any row in the joined table.
More than one join
It’s also not uncommon to add more than one join to a single statement. There is no additional syntax required. You only have to write a second (a third, and so on) join:

— more than one inner join
SELECT *
FROM tableA a
INNER JOIN tableB b
ON a.someColumn = b.otherColumn
INNER JOIN tableC c
ON b.anotherColumn = c.nextColumn

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s