我有两张桌子:
Table A
id name
--- -----
1 Foo
2 Bar
3 Fred
4 Joe
Table B
id tablea_id result date
--- ---- ---- ---
1 1 A 02/04/2015
2 2 A 02/04/2015
3 1 B 03/04/2015
4 1 C 04/04/2015
我如何能够获得看起来像这样的结果集?为了“循环”表A中的内容,我需要加入什么?
date tablea_id result
--- --- ----
02/04/2015 1 A
02/04/2015 2 A
02/04/2015 3 NULL
02/04/2015 4 NULL
03/04/2015 1 B
03/04/2015 2 NULL
03/04/2015 3 NULL
03/04/2015 4 NULL
04/04/2015 1 C
04/04/2015 2 NULL
04/04/2015 3 NULL
04/04/2015 4 NULL
答案 0 :(得分:2)
您希望cross join
生成所有行,并希望left join
引入现有值:
select d.date, a.tablea_id, b.result
from a cross join
(select distinct date from b) d left join
b
on b.tablea_id = a.tablea_id and b.date = d.date
order by d.date, a.tablea_id;
答案 1 :(得分:0)
我需要什么加入
OUTER JOIN
并且最有可能(根据您发布的预期结果)LEFT OUTER JOIN
答案 2 :(得分:0)
select ab.id,ab.date,b.result
from
(select a.id,b.date
from(select distinct id
from table_a)a,
(select distinct date
from table_b)b)ab
left outer join
table_b b
on ab.id=b.id
and ab.date=b.date
答案 3 :(得分:0)
使用Full Outer Join检查此简单查询。 Live Demo
select distinct a.date,a.id as tablea_id ,result from B b
full outer join
(
select a.id,b.date from B b,A a
)A on a.id=b.tablea_id and a.date=b.date