我在加入两个表的内容时遇到了一些麻烦。这是目前的情况:
买
文章 购买 年度
1 12400 2011
1 28000 2012
1 46351 2015
已售出
文章 已售出 年度
1 6400 2011
1 12000 2013
1 60900 2014
期望的结果
文章 购买 已售出 年
1 12400 6400 2011
1 28000 NULL 2012
1 NULL 12000 2013
1 NULL 60900 2014
1 46351 NULL 2015
我已尝试以下方法来达到预期效果:
SELECT b.article, b.bought, s.sold, b.year
FROM Bought AS b
LEFT JOIN Sold as s ON s.article = b.article AND s.year = b.year
WHERE b.article = '1'
ORDER BY b.year
这仅返回2011年的结果(两个值均存在)。
使用包含所有文章的第三个表的另一个尝试返回了相同的错误结果,并且它有两年的列,这是不理想的:
SELECT art.article, b.bought, s.sold, b.year, s.year
FROM articles AS art
LEFT OUTER JOIN bought AS b ON art.article = b.article
LEFT OUTER JOIN Sold AS s ON art.article = s.article
AND (b.year = s.year OR b.year IS NULL OR s.year IS NULL)
WHERE art.article = '1'
我尝试在最后一个SQL语句中使用不同类型的连接,但它们似乎都不起作用。 我怎样才能达到预期的效果?
答案 0 :(得分:11)
听起来你想要full outer join
:
SELECT coalesce(b.article, s.article) as article, b.bought, s.sold,
coalesce(b.year, s.year) as year
FROM Bought b FULL OUTER JOIN
Sold s
ON s.article = b.article AND s.year = b.year
WHERE (b.article = '1' OR s.article = '1')
ORDER BY year
答案 1 :(得分:4)
您应该使用full outer join
:
select coalesce(b.article, s.article)
, b.bought
, s.sold
, coalesce (b.year, s.year) as year
from Bought b
full join Sold s on s.article = b.article
and s.year = b.year
where coalesce(b.article, s.article) = '1'
order by year
答案 2 :(得分:0)
你可以做一个工会。首先选择左连接,然后将已售出的结果合并到已购买的相应行中。
SELECT b.article, b.bought, s.sold, b.year
FROM Bought AS b
LEFT JOIN Sold as s ON s.article = b.article AND s.year = b.year
where article = 1
Union
SELECT article,null, sold, year
FROM sold where article =1 and year not in (select year from bought)
这样的事情。我没有测试过,但你可以得到这个想法。