菜单
×
   ❮   
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 INNER JOIN


INNER JOIN

INNER JOIN 关键字会选择两个表中都具有匹配值的记录。

让我们看一个使用我们的模拟 testproducts 表的示例

 testproduct_id |      product_name      | category_id
----------------+------------------------+-------------
              1 | Johns Fruit Cake       |           3
              2 | Marys Healthy Mix      |           9
              3 | Peters Scary Stuff     |          10
              4 | Jims Secret Recipe     |          11
              5 | Elisabeths Best Apples |          12
              6 | Janes Favorite Cheese  |           4
              7 | Billys Home Made Pizza |          13
              8 | Ellas Special Salmon   |           8
              9 | Roberts Rich Spaghetti |           5
            10 | Mias Popular Ice        |          14
(10 行)

我们将尝试将 testproducts 表与 categories 表连接。

 category_id | category_name  |                       description
-------------+----------------+------------------------------------------------------------
           1 | Beverages      | Soft drinks, coffees, teas, beers, and ales
           2 | Condiments     | Sweet and savory sauces, relishes, spreads, and seasonings
           3 | Confections    | Desserts, candies, and sweet breads
           4 | Dairy Products | Cheeses
           5 | Grains/Cereals | Breads, crackers, pasta, and cereal
           6 | Meat/Poultry   | Prepared meats
           7 | Produce        | Dried fruit and bean curd
           8 | Seafood        | Seaweed and fish
(8 行)

请注意,testproducts 表中的许多产品具有 category_id,该 ID 在 categories 表中不匹配任何类别。

使用 INNER JOIN 时,不会返回没有匹配项的记录,只会返回同时匹配两个表的记录。

示例

使用 category_id 列将 testproducts 连接到 categories

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

结果

仅返回两个表中都有匹配项的记录。

 testproduct_id |      product_name      | category_name
----------------+------------------------+----------------
              1 | Johns Fruit Cake       | Confections
              6 | Janes Favorite Cheese  | Dairy Products
              8 | Ellas Special Salmon   | Seafood
              9 | Roberts Rich Spaghetti | Grains/Cereals
(4 行)

注意: JOININNER JOIN 的结果相同。

INNERJOIN 的默认连接类型,因此当您编写 JOIN 时,解析器实际上会将其写为 INNER JOIN


PostgreSQL 练习

通过练习来测试自己

练习

选择正确的 JOIN 子句,以从两个表中选取在两者中都有匹配项的所有记录。

SELECT * FROM orders
 customers
ON orders.customer_id = customers.customer_id;
        

开始练习


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持