PostgreSQL 右连接


右连接

这个RIGHT JOIN关键字从 "right" 表中选择所有记录,并从 "left" 表中选择匹配的记录。如果没有匹配,则结果是从左侧开始 0 条记录。

让我们看一个使用我们的虚拟对象的例子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 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)

笔记:许多产品在testproducts有一个category_id与中的任何类别都不匹配categories表格。

通过使用RIGHT JOIN我们将从中获取所有记录categories,即使是那些没有匹配的testproducts表格:

示例

加入testproducts categories使用category_id柱子:

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

结果

所有记录来自categories,并且只有来自的匹配记录testproducts:

 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
                |                        | Condiments
                |                        | Meat/Poultry
                |                        | Beverages
                |                        | Produce
(8 rows)

笔记:RIGHT JOIN RIGHT OUTER JOIN会给出相同的结果。

OUTER是默认的连接类型RIGHT JOIN,所以当你写RIGHT JOIN解析器实际上写的是RIGHT OUTER JOIN


PostgreSQL 练习

通过练习测试一下

练习:

选择正确的 JOIN 子句来选择所有记录customers表加上所有匹配项orders表格:

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

开始练习