📜  PostgreSQL INNER Join(1)

📅  最后修改于: 2023-12-03 15:03:49.169000             🧑  作者: Mango

PostgreSQL INNER JOIN

PostgreSQL INNER JOIN is a type of join that returns only the rows that have matching values in both tables being joined. This means that only the rows with corresponding values in both tables will be displayed in the result set.

Syntax

The syntax for the PostgreSQL INNER JOIN is as follows:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
  • column_name(s) - the column or columns to be displayed in the result set.
  • table1 - the first table to be joined.
  • table2 - the second table to be joined.
  • ON table1.column_name = table2.column_name - the condition that specifies how the tables are joined.
Example

Let's say we have two tables customers and orders with the following data:

customers table:

| id | first_name | last_name | |----|------------|-----------| | 1 | John | Smith | | 2 | Mike | Johnson | | 3 | Sarah | Williams | | 4 | Lisa | Brown |

orders table:

| id | customer_id | product | quantity | |----|------------|-----------|----------| | 1 | 1 | Widget A | 3 | | 2 | 2 | Widget B | 5 | | 3 | 1 | Widget C | 2 | | 4 | 4 | Widget D | 1 | | 5 | 3 | Widget E | 4 |

To join these two tables and to display the customer's first name, last name, and the product they ordered, we would use the following INNER JOIN statement:

SELECT customers.first_name, customers.last_name, orders.product
FROM customers
INNER JOIN orders
ON customers.id = orders.customer_id;

This would result in:

| first_name | last_name | product | |------------|-----------|----------| | John | Smith | Widget A | | Mike | Johnson | Widget B | | John | Smith | Widget C | | Lisa | Brown | Widget D | | Sarah | Williams | Widget E |

As you can see, only the rows with corresponding values in both tables were displayed in the result set.

Conclusion

PostgreSQL INNER JOIN is a useful operator that allows programmers to combine data from two or more tables based on matching values in a specific column. By understanding the syntax and how it works, programmers can retrieve the exact data they need from their PostgreSQL database with ease.