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 行)
我們將嘗試將 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
表中的任何類別都不匹配。
使用 LEFT JOIN
,我們將獲得 testpoducts
中的所有記錄,即使那些在 categories
表中沒有匹配項的記錄。
示例
使用 category_id
列將 testproducts
連線到 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 行)
注意: LEFT JOIN
和 LEFT OUTER JOIN
會產生相同的結果。
OUTER
是 LEFT JOIN
的預設連線型別,因此當您編寫 LEFT JOIN
時,解析器實際上會將其寫為 LEFT OUTER JOIN
。