PostgreSQL LEFT JOIN
LEFT JOIN
LEFT JOIN 关键字从“左”表中选择所有记录,并从“右”表中选择匹配的记录。如果没有匹配项,则右侧的结果为 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 中的许多产品都有一个与 categories 表中的任何类别都不匹配的 category_id。
通过使用 LEFT JOIN,我们将从 testproducts 中获取所有记录,甚至是 categories 表中不匹配的记录:
实例
使用 category_id 列将 testproduct 与 categories 连接:
SELECT testproduct_id, product_name, category_name FROM testproducts LEFT JOIN categories ON testproducts.category_id = categories.category_id;
结果
从 testproducts 中选择所有记录,并且只从 categories 中选择匹配的记录:
testproduct_id | product_name | category_name
----------------+------------------------+----------------
1 | Johns Fruit Cake | Confections
2 | Marys Healthy Mix |
3 | Peters Scary Stuff |
4 | Jims Secret Recipe |
5 | Elisabeths Best Apples |
6 | Janes Favorite Cheese | Dairy Products
7 | Billys Home Made Pizza |
8 | Ellas Special Salmon | Seafood
9 | Roberts Rich Spaghetti | Grains/Cereals
10 | Mias Popular Ice |
(10 rows)
注意:LEFT JOIN 和 LEFT OUTER JOIN 将给出相同的结果。
OUTER 是 LEFT JOIN 的默认连接类型,因此当您编写 LEFT JOIN 时,解析器实际上会编写 LEFT OUTER JOIN。