📜  SQL right-join(1)

📅  最后修改于: 2023-12-03 14:47:35.283000             🧑  作者: Mango

SQL Right Join

Introduction

SQL right join is a type of join operation in SQL that returns all the rows from the right table and matching rows from the left table. If there is no match, then NULL values are returned for the left table's columns.

In a right join, the right table is the main table, and all the data from the right table is included in the result set, regardless of whether it matches any rows in the left table.

Syntax

The basic syntax for a right join is as follows:

SELECT
    column1,
    column2,
    ...
FROM
    table1
RIGHT JOIN
    table2
ON
    table1.column = table2.column;

In this syntax, table1 is the left table, table2 is the right table, and the ON clause specifies the join condition.

Example

Consider two tables, customers and orders, with the following data:

customers table:

| id | name | |---|----------| | 1 | Alice | | 2 | Bob | | 3 | Charlie | | 4 | Dave | | 5 | Eve |

orders table:

| id | customer_id | amount | |---|-------------|--------| | 1 | 2 | 100 | | 2 | 3 | 200 | | 3 | 2 | 150 | | 4 | 4 | 50 |

To retrieve all customers and their orders, including customers with no orders, we can use a right join as follows:

SELECT
    customers.name,
    orders.amount
FROM
    orders
RIGHT JOIN
    customers
ON
    orders.customer_id = customers.id;

The result of this query will be:

| name | amount | |----------|--------| | Alice | NULL | | Bob | 100 | | Bob | 150 | | Charlie | 200 | | Dave | 50 | | Eve | NULL |

Conclusion

SQL right join is a useful tool for retrieving all the data from the right table and combining it with matching data from the left table, including cases where there is no match. By understanding the syntax and usage of right join, programmers can write more efficient and effective SQL queries.