PostgreSQL RIGHT JOIN
RIGHT JOIN
RIGHT 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,它与 categories 表中的任何类别都不匹配。
通过使用 RIGHT JOIN,我们将获得 categories 表中的所有记录,即使是那些在 testproducts 表中没有匹配项的记录。
示例
使用 category_id 列将 testproducts 连接到 categories。
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 行)
注意: RIGHT JOIN 和 RIGHT OUTER JOIN 的结果是相同的。
OUTER 是 RIGHT JOIN 的默认连接类型,所以当你写 RIGHT JOIN 时,解析器实际上会写成 RIGHT OUTER JOIN。