问题是您要加入的表中有多个匹配项。实际上,您的代码说:
select *
from parent
left outer join child on parent.id = child.parentId
如果父母有两个孩子,你会得到两个;所以父母出现了两次。
如果您只想在需要妥协时得到父母;你不能同时拥有两个孩子。对子表中的列执行聚合函数并对父表中的列执行分组,或者rownumber() over partition by (list,of,parent,columns order by list,of,child,columns) r
在内部语句和where r=1
外部语句中使用,如下所示:
select p.id, p.name, max(c.id), max(c.name) --nb: child id and name may come from different records
from parent p
left outer join child c on parent.id = child.parentId
group by p.id, p.name
或者
select *
from
(
select p.id, p.name, c.id, c.name
, rownumber() over (partition by p.id order by c.id desc) r
from parent p
left outer join child c on parent.id = child.parentId
) x
where x.r = 1
更新
如评论中所述,如果子数据完全相同,您可以这样做:
select p.id, p.name, c.name
from parent p
left outer join
(
select distinct c.parentId, c.name
from child
) c on parent.id = child.parentId
或(如果有几个字段不同但您不在乎得到哪个字段)
select p.id, p.name, c.id, c.name
from parent p
left outer join
(
select max(c.id) id, c.parentId, c.name
from child
group by c.parentId, c.name
) c on parent.id = child.parentId