你想做这样的事情吗?
select c.id
,c.name
,count(*)
,count(s.company_id_source) as num_sources
,count(t.company_id_target) as num_targets
from company c
left join company_mapping s on(s.company_id_source = c.id)
left join company_mapping t on(t.company_id_target = c.id)
where c.name like 'foobar%'
group
by c.id
,c.name
having count(s.company_id_source) > 1
or count(t.company_id_target) > 1;
编辑:下面的新查询以响应评论。查询现在返回:匹配“Foobar”的所有公司,无论它们在表 company_mapping 中是否有关联行,以及:
- num_sources:company_mapping 中以公司为来源的行数。
- num_targets:company_mapping 中以公司为目标的行数。
- num_mappings:company_mapping 中“连接”的编号(源或目标)
.
select c.id
,c.name
,count(s.company_id_source) + count(t.company_id_target) as num_mappings
,count(s.company_id_source) as num_sources
,count(t.company_id_target) as num_targets
from company c
left join company_mapping s on(s.company_id_source = c.id)
left join company_mapping t on(t.company_id_target = c.id)
where c.name like 'foobar%'
group
by c.id
,c.name;