📜  PostgreSQL – 左连接(1)

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

PostgreSQL – 左连接

在 PostgreSQL 中,LEFT JOIN 是最常用的连接操作之一。它返回包括左表中的所有行和右表中匹配的行的所有行。如果右表中没有与左表中的任何行匹配的行,则会返回 NULL。

语法
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2 ON condition;

其中:

  • column1, column2, ...是要检索的列名;
  • table1是左表;
  • table2是右表;
  • condition是连接条件,即两个表的共同列。
示例

假设我们有两个表:customersorders

  • customers 表:
id  | name      | email
----|-----------|------------------
1   | John Doe  | johndoe@mail.com
2   | Jane Smith| janesmith@mail.com
3   | Bob Brown | bobbrown@mail.com
  • orders 表:
id  | customer_id | product
----|------------|-----------------
1   | 1          | iPhone
2   | 2          | Macbook
3   | 3          | iPad

现在,我们想要获取所有客户和他们的订单(如果有的话)。我们可以使用以下查询:

SELECT customers.name, orders.product
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id;

查询结果如下:

name       | product
-----------|-----------
John Doe   | iPhone
Jane Smith | Macbook
Bob Brown  | iPad

注意,Bob Brown 没有订单,因此在 product 列中显示 NULL。

总结

LEFT JOIN 是一种非常有用的连接方法,它可以帮助我们获取左表中的所有行和右表中与左表中的行匹配的行。在使用时,务必注意连接条件的正确性,以免出现错误的结果。