Syntax
Here are syntax examples for the impatient. Basically, ANSI-style join conditions can be specified with two different keywords: USING and ON. Take a look at the following examples:
1
2
3
4
| -- inner join with USING clauseSELECT *FROM <firstTable> a INNER JOIN <anotherTable> bUSING(<columnName>) |
1
2
3
4
| -- inner join with ON clauseSELECT *FROM <firstTable> a INNER JOIN <anotherTable> bON a.<someColumn> = b.<anotherColumn> |
Basics
Probably 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
1
2
3
4
5
| -- INNER JOIN with ON clauseSELECT *FROM tableA aINNER JOIN tableB bON a.someColumn = b.otherColumn |
1
2
3
4
5
| -- INNER JOIN with USING clauseSELECT *FROM tableA aINNER JOIN tableB bUSING(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.
1
2
3
| -- inner join without a condition: cross joinSELECT *FROM <firstTable> CROSS JOIN <anotherTable> |
Inner Join vs Outer Join
The major difference between outer and inner joins is: an outer join is able to identify rows that were not matched by any row in the joined table. Therefor, if you’re searching for rows from tableA that have no related entry in tableB at all, you have to use an outer join. Please see the tutorial about outer joins for a more information.More than one join
It’s also very common to add more than one join to a single statement. There is no special syntax required. You only have to write a second (a third, and so on) join:
1
2
3
4
5
6
7
| -- more than one inner joinSELECT *FROM tableA aINNER JOIN tableB bON a.someColumn = b.otherColumnINNER JOIN tableC cON b.anotherColumn = c.nextColumn |
Inner Join with comma operator
An inner join can also be written with the help of the so called comma operator. Please read the dedicated tutorial about writing inner joins with the comma operator for more information.You can host your MySQL projects on regular web hosting packages or a dedicated server. Nowadays, all of them should support inner joins.
No comments:
Post a Comment