繁体   English   中英

内连接和左外连接组合 - 有两列

[英]inner and left outer join combined - with two columns

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

表1:早餐

动物 食物
奶牛
香蕉
苹果
人类 谷物
鳄鱼

表 2:午餐

动物 食物
奶牛
苹果
人类 三明治
鳄鱼

您将如何编写查询以返回所有动物但返回午餐与早餐不同的 NULL?

预期 output:

动物 早餐 午餐
奶牛
香蕉 NULL
苹果 苹果
人类 谷物 NULL
鳄鱼

这是一个简单的外部连接:

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

您将使用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 Server等,所以我只是猜测它可能是这两者中的任何一个。

它只是一个左连接语句,记住左连接返回左表中的所有索引,未配对的用'null'值填充,查询看起来像

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

我们使用两个表中的 Food 列作为索引。 拿索引“肉”然后你让鳄鱼吃肉作为早餐和午餐,所以你的 output 行是

| croc | meat | meat |

现在采用索引“谷物”,我们有人类早餐吃谷物,但人类午餐没有谷物,然后(当您选择左连接时)值“Null”放置在午餐列中,所以我们有

| human | cereal | null |

作为 output 行。

暂无
暂无

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

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