如果未找到匹配项,则左连接为空结果

时间:2010-09-08 16:08:28

标签: sql mysql

说我有这三个表:

Table: Baskets
id  |  name
1      Sale
2      Premium
3      Standard
4      Expired

Table: Fruit
id  |  name   | basketid
1      Apples    1
2      Oranges   2
3      Grapes    3
4      Apples    2
5      Apples    4

Table: Veggies
id  |  name   | basketid
1      Carrots     1
2      Peas        2
3      Asparagus   1

看起来第二个两个表应该只是一个名为produce的表,但在实际情况下,它们有充分的理由成为不同的表。如果篮子在水果或蔬菜表中有行,我需要编写一个返回行的连接。我想我可以通过两个左连接完成这个:

Select Baskets.*, fruit.name as fruit,
veggies.name as veggies 
from Baskets
left join Fruit on Baskets.id =  Fruit.basketid 
left join veggies on Baskets.id = Veggies.basketid 
where Baskets.id = 2;

但是这个语句返回我想要为空的字段中的值。实际输出:

id  | name     |  fruit   |  veggies
2     Premium    Oranges     Peas
2     Premium    Apples      Peas

我想要的输出:

id  | name     |  fruit   |  veggies
2     Premium    Oranges     
2     Premium    Apples      
2     Premium               Peas

我该如何做到这一点?

2 个答案:

答案 0 :(得分:4)

你需要将水果和蔬菜表联合成一个你加入的关系,一个la:

Select Baskets.*, produce.fruitname as fruit, produce.veggiename as veggies 
from Baskets
left join (SELECT basketid, name as fruitname, NULL as veggiename
           FROM fruit
           UNION
           SELECT basketid, NULL, name
           FROM veggies) produce
      ON baskets.id = produce.basketid
where Baskets.id = 2;

答案 1 :(得分:2)

如果篮子中没有任何内容,此查询将不返回任何行:

SELECT  baskets.*, fruit.name AS fruit, NULL AS veggie
FROM    baskets
JOIN    fruit
ON      fruit.basketId = baskets.id
WHERE   baskets.Id = 2
UNION
SELECT  baskets.*, NULL, veggie.name
FROM    baskets
JOIN    veggies
ON      veggies.basketId = baskets.id
WHERE   baskets.Id = 2

如果购物篮中没有任何内容,此查询将返回包含两个NULLS的单行:

SELECT  baskets.*, fruit.name AS fruit, NULL AS veggie
FROM    baskets
LEFT JOIN
        fruit
ON      fruit.basketId = baskets.id
WHERE   baskets.Id = 2
UNION
SELECT  baskets.*, NULL, veggie.name
FROM    baskets
LEFT JOIN
        veggies
ON      veggies.basketId = baskets.id
WHERE   baskets.Id = 2

这假定fruit.nameveggie.name都不可为空并且是唯一的。

此查询与之前的查询相同,但效率更高:

SELECT  baskets.*, fruit.name AS fruit, NULL AS veggie
FROM    baskets
JOIN    fruit
ON      fruit.basketId = baskets.id
WHERE   baskets.Id = 2
UNION ALL
SELECT  baskets.*, NULL, veggie.name
FROM    baskets
JOIN    veggies
ON      veggies.basketId = baskets.id
WHERE   baskets.Id = 2
UNION ALL
SELECT  baskets.*, NULL, NULL
FROM    baskets
LEFT JOIN
        fruit
ON      fruit.basketId = baskets.id
LEFT JOIN
        veggies
ON      veggies.basketId = baskets.id
WHERE   baskets.Id = 2
        AND fruit.basketId IS NULL
        AND veggies.basketId IS NULL

,并且不承担任何责任。