内部和左外部联接组合 - 两列

inner and left outer join combined - with two columns

刚刚学习 - 感谢您的帮助。

Table1:早餐

Animal Food
Cow Grass
Monkey Banana
Monkey Apples
Human Cereal
Croc Meat

Table 2: 午餐

Animal Food
Cow Grass
Monkey Apples
Human Sandwich
Croc Meat

您将如何向 return 所有动物编写查询,但 return NULL 午餐与早餐不同?

预期输出:

Animal Breakfast Lunch
Cow Grass Grass
Monkey Banana NULL
Monkey Apples Apples
Human Cereal NULL
Croc Meat Meat

你会使用 full join:

select coalesce(b.animal, l.animal) as animal,
       b.food as breakfast, l.food as lunch
from breakfast b full join
     lunch l
     on b.animal = l.animal

取决于您使用的 sql 类型:

如果SQLite:

SELECT 
breakfast.animal AS animal, 
breakfast.food AS breakfast, 
CASE WHEN lunch.food=breakfast.food THEN lunch.food ELSE NULL END AS lunch 
FROM breakfast JOIN lunch ON breakfast.animal = lunch.animal;

否则如果MySQL:

SELECT 
breakfast.animal AS animal, 
breakfast.food AS breakfast, 
IF lunch.food=breakfast.food THEN lunch.food ELSE NULL END IF AS lunch 
FROM breakfast JOIN lunch ON breakfast.animal = lunch.animal;

还有其他类型的 SQL,例如 SQL 服务器等,所以我只是猜测它可能是这两种中的任何一种。

这是一个普通的外部连接:

select
   b.animal,
  ,b.food as breakfast
  ,l.food as lunch
from breakfast b 
left join lunch l
  on b.animal = l.animal
 and a.food = b.food

就是一个left join语句,记住left join returns left table中的所有索引,没有配对的用'null'值填充,query看起来像

 select b.Animal, 
    b.Food as Breakfast, 
    l.Food as Lunch
from Breakfast as b
    left join Lunch as l
using(Food);

我们使用 table 中的 Food 列作为索引。 取索引 'meat' 然后你让鳄鱼吃肉作为早餐和午餐所以你的输出行是

| croc | meat | meat |

现在取索引 'cereal',我们知道人类早餐吃麦片,但午餐不吃麦片,然后(当您选择左连接时)值 'Null' 放在午餐栏所以我们有

| human | cereal | null |

作为输出行。