Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

PostgreSQL 连接


连接

一个 JOIN 子句用于基于两个或多个表之间相关的列,组合来自这些表中的行。

让我们看一下来自 products 表的选择

 product_id |  product_name  | category_id
------------+----------------+-------------
         33 | Geitost        |           4
         34 | Sasquatch Ale  |           1
         35 | Steeleye Stout |           1
         36 | Inlagd Sill    |           8

然后,查看来自 categories 表的选择

 category_id | category_name
-------------+----------------
           1 | Beverages
           2 | Condiments
           3 | Confections
           4 | Dairy Products

注意 products 表中的 category_id 列引用了 categories 表中的 category_id。上面两个表之间的关系是 category_id 列。

然后,我们可以创建以下 SQL 语句(使用 JOIN),它选择两个表中具有匹配值的记录

示例

使用 category_id 列将 products 连接到 categories

SELECT product_id, product_name, category_name
FROM products
INNER JOIN categories ON products.category_id = categories.category_id;
运行示例 »

如果我们从上面 products 表中提取相同的选择,我们将得到以下结果

结果

 product_id |  product_name  | category_name
------------+----------------+----------------
         33 | Geitost        | Dairy Products
         34 | Sasquatch Ale  | Beverages
         35 | Steeleye Stout | Beverages
         36 | Inlagd Sill    | Seafood

不同类型的连接

以下是 PostgreSQL 中不同类型的连接

  • INNER JOIN:返回两个表中都具有匹配值的记录
  • LEFT JOIN:返回左侧表中的所有记录,以及右侧表中匹配的记录
  • RIGHT JOIN:返回右侧表中的所有记录,以及左侧表中匹配的记录
  • FULL JOIN:在左侧或右侧表中存在匹配时返回所有记录

PostgreSQL 练习

通过练习测试自己

练习

在 JOIN 子句中插入缺失的部分,以使用两个表 orderscustomers 中的 customer_id 字段作为关系来连接这两个表

SELECT * FROM orders
LEFT JOIN customers
 = ;
        

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.