简体   繁体   English

SQL连接排除数据

[英]SQL Joins Excluding Data

Say I have three tables: 说我有三个表:

Fruit (Table 1)
------
Apple
Orange
Pear
Banana

Produce Store A (Table 2 - 2 columns: Fruit for sale => Price)
-------------------------
Apple => 1.00
Orange => 1.50
Pear => 2.00

Produce Store B (Table 3 - 2 columns: Fruit for sale => Price)
------------------------
Apple => 1.10
Pear => 2.50
Banana => 1.00

If I would like to write a query with Column 1: the set of fruit offered at Produce Store A UNION Produce Store B, Column 2: Price of the fruit at Produce Store A (or null if that fruit is not offered), Column 3: Price of the fruit at Produce Store B (or null if that fruit is not offered), how would I go about joining the tables? 如果我想对第1列写一个查询:农产品商店A UNION农产品商店B中提供的水果集,第2列:农产品商店A中水果的价格(如果未提供该水果,则为null),第3列:农产品商店B中水果的价格(如果未提供该水果,则为null),我将如何加入餐桌?

I am facing a similar problem (with more complex tables), and no matter what I try, if the "fruit" is not at "produce store a" but is at "produce store b", it is excluded (since I am joining produce store a first). 我面临类似的问题(具有更复杂的表),无论我尝试什么,如果“水果”不在“农产品商店a”,而是在“农产品商店b”,则将其排除在外(因为我正在加入生产商店第一)。 I have even written a subquery to generate a full list of fruits, then left join Produce Store A, but it is still eliminating the fruits not offered at A. Any Ideas? 我什至写了一个子查询来生成水果的完整列表,然后离开加入Produce Store A,但是它仍然消除了A中未提供的水果。任何想法吗?

The key is to use a left join . 关键是使用left join This will include columns from the left side table even if there is no matching row in the right side table. 即使右侧表中没有匹配的行,也将包括左侧表中的列。

For example: 例如:

select f.name, a.price, b.price
from Fruit f
left join ProduceStoreA a on a.Name = f.Name
left join ProduceStoreB b on b.Name = f.Name

If a fruit is not found in Store A, the second column will be null . 如果在商店A中找不到水果,则第二列将为null If it's not found in Store B, the third column will be null . 如果在商店B中找不到,则第三列将为null If neither sells the fruit, both column two and three will be null . 如果两个都不卖水果,则第二列和第三列都将为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM