必须使用 group by 来给出一组值的聚合函数的结果(例如接收不同类型的计数或值的总和)。如果您也只需要获取一个人属于哪一组类型,则可以使用这样的单个查询。
select name, types
from people inner join
(mapping inner join types on mapping.guid = types.guid)
on people.wpid = mapping.wpid
where people.wpid in (select people.wpid from people inner join
(mapping inner join types on mapping.guid = types.guid)
on people.wpid = mapping.wpid where types.type = 'politician')
一个分组将有助于了解一个政治家进入了多少个群体
select name, count(types)
from people inner join
(mapping inner join types on mapping.guid = types.guid)
on people.wpid = mapping.wpid
where people.wpid in (select people.wpid from people inner join
(mapping inner join types on mapping.guid = types.guid)
on people.wpid = mapping.wpid where types.type = 'politician')
group by name
编辑:避免 IN 子查询
如果你知道政治团体的指导,你可以做这样的事情。我没有测试查询,但想法是使用与映射表的联接过滤人员表,其中 guid 等于政治家 guid
select p.name, count(t.types)
from people p inner join mapping m1
on p.wid = m1.wid and m1.guid = [politician guid]
inner join mapping m2
on p.wid = m2.wid
inner join types t
in m2.guid = t.guid