A2-02-15.DML-MySQL RIGHT JOIN

转载自:http://www.mysqltutorial.org/mysql-right-join/

MySQL RIGHT JOIN

 

Summary: in this tutorial, you will learn how to use the MySQL RIGHT JOIN to query data from two or more tables.

Introduction to MySQL RIGHT JOIN clause

MySQL RIGHT JOIN is similar to LEFT JOIN, except the treatment of table reversed.

The following statement queries data from two tables t1 and t2 using the RIGHT JOIN clause:

In this statement:

  • t1 is the left table and t2 is the right table
  • join_predicate is the condition to match rows on the left table (t1) with rows on the right table (t2)

The join_predicate could be in the following form:

or if the common columns of the two table have the same name, you can use the following syntax:

The following describes how the RIGHT JOIN clause works.

  • All rows from the t2 table (right table) will appear at least once in the result set.
  • Based on the join_predicate, if no matching row from the t1 table (left table) exists, NULL will appear in columns from the t1 table for the rows that have no match in the t2 table.

It is important to emphasize that RIGHT JOIN and LEFT JOIN clauses are functionally equivalent and they can replace each other as long as the table order is switched.

Note that the RIGHT OUTER JOIN is a synonym for RIGHT JOIN.

MySQL RIGHT JOIN example

Suppose we have two tables t1 and t2 with the following structures and data:

The following query joins two tables t1 and t2 using the pattern column:

MySQL RIGHT JOIN result

The picture below illustrates the result of the RIGHT JOIN clause:

MySQL RIGHT JOIN

See the following employees and customers in the sample database.

The following query get the sales representatives and their customers:

MySQL RIGHT JOIN example

Because we used RIGHT JOIN, all customers (right table) appears in the result set. We also found that some customers do not have dedicated sales rep indicated by NULL in the salesman column.

In this tutorial, you have learned how to use the MySQL RIGHT JOIN to query data from two or more tables.

posted @ 2018-08-22 14:33  zhuntidaoren  阅读(186)  评论(0编辑  收藏  举报