PostgreSQL 内连接(INNER JOIN)
INNER JOIN
INNER JOIN 关键字选择两个表中具有匹配值的记录。
让我们看一个使用我们的 testproducts 表的例子:
testproduct_id | product_name | category_id----------------+------------------------+-------------1 | Johns Fruit Cake | 32 | Marys Healthy Mix | 93 | Peters Scary Stuff | 104 | Jims Secret Recipe | 115 | Elisabeths Best Apples | 126 | Janes Favorite Cheese | 47 | Billys Home Made Pizza | 138 | Ellas Special Salmon | 89 | Roberts Rich Spaghetti | 510 | Mias Popular Ice | 14(10 rows)
我们将尝试将 testproducts 表与 categories 表连接起来:
category_id | category_name | description-------------+----------------+------------------------------------------------------------1 | Beverages | Soft drinks, coffees, teas, beers, and ales2 | Condiments | Sweet and savory sauces, relishes, spreads, and seasonings3 | Confections | Desserts, candies, and sweet breads4 | Dairy Products | Cheeses5 | Grains/Cereals | Breads, crackers, pasta, and cereal6 | Meat/Poultry | Prepared meats7 | Produce | Dried fruit and bean curd8 | Seafood | Seaweed and fish(8 rows)
请注意,testproducts 中的许多产品的 category_id 与 categories 表中的任何类别都不匹配。
通过使用 INNER JOIN,我们不会得到不匹配的记录,我们只会得到与两个表匹配的记录:
实例
使用 category_id 列将 testproducts 表和 categories 表关联起来:
SELECT testproduct_id, product_name, category_nameFROM testproductsINNER JOIN categories ON testproducts.category_id = categories.category_id;
结果
仅返回 BOTH 表中匹配的记录:
testproduct_id | product_name | category_name----------------+------------------------+----------------1 | Johns Fruit Cake | Confections6 | Janes Favorite Cheese | Dairy Products8 | Ellas Special Salmon | Seafood9 | Roberts Rich Spaghetti | Grains/Cereals(4 rows)
注意:JOIN 和 INNER JOIN 将给出相同的结果。
INNER 是 JOIN 的默认联接类型,所以当您编写 JOIN 时,解析器实际上会编写 INNER JOIN。