PostgreSQL INNER JOIN

INNER JOIN

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

让我们使用一个虚拟的测试产品表作为例子:

 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 rows)

我们将尝试把 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 rows)

请注意,测试产品中的许多产品都有一个 category_id,它与 categories 表中的任何类别都不匹配。

通过使用 INNER JOIN,我们不会获取不匹配的记录,我们只能获取两个表都匹配的记录:

实例

使用 category_id 列将 testproduct 与 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 rows)

注意:JOININNER JOIN 将给出相同的结果。

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