📜  sql join 3 个表 - SQL (1)

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

SQL Join 3 Tables

When working with databases, it is often necessary to join multiple tables together to retrieve the desired information. In SQL, this can be accomplished by using the JOIN keyword.

Types of Joins

There are several types of JOINs including:

  • INNER JOIN: returns only the matching rows from both tables
  • LEFT JOIN: returns all rows from the left table and the matching rows from the right table
  • RIGHT JOIN: returns all rows from the right table and the matching rows from the left table
  • FULL OUTER JOIN: returns all rows from both tables
Syntax

The basic syntax for joining three tables is:

SELECT *
FROM table1
JOIN table2 ON table1.column = table2.column
JOIN table3 ON table2.column = table3.column;
Example

Suppose we have three tables: users, orders, and order_items.

users table:

| user_id | name | | ------- | ----- | | 1 | Alice | | 2 | Bob | | 3 | Carol |

orders table:

| order_id | user_id | | -------- | ------- | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 1 |

order_items table:

| order_id | item | quantity | | -------- | ------- | -------- | | 1 | Apples | 2 | | 1 | Oranges | 3 | | 2 | Pears | 4 | | 3 | Bananas | 1 | | 4 | Grapes | 2 |

To retrieve a list of all orders and their corresponding items along with the user's name, we can use the following SQL query:

SELECT users.name, orders.order_id, order_items.item, order_items.quantity
FROM users
JOIN orders ON users.user_id = orders.user_id
JOIN order_items ON orders.order_id = order_items.order_id;

This will produce the following result:

| name | order_id | item | quantity | | ----- | -------- | ------- | -------- | | Alice | 1 | Apples | 2 | | Alice | 1 | Oranges | 3 | | Bob | 2 | Pears | 4 | | Carol | 3 | Bananas | 1 | | Alice | 4 | Grapes | 2 |

Conclusion

Joining multiple tables in SQL can be complex, but by using the appropriate JOIN keyword and syntax, querying data from multiple tables can be seamless.