在Postgresql中选择group by子句和多个内连接的查询

时间:2012-11-12 13:37:41

标签: sql postgresql group-by having-clause

我有3个表格,其中包含以下定义

people
------
- wid 
- name

types
-----
- guid
- type

mapping
-------
- guid
- wid

人员表中有人员列表

types表列出了people表中每行的类型信息。如果一个人属于多个类型,则类型表中会出现两行。

映射表提供了人员和类型表之间的映射。

现在要找出谁是“政治家”类型的人,我可以使用以下查询。

select name from people inner join 
(mapping inner join types on mapping.guid = types.guid) 
on people.wpid = mapping.wpid where types.type = 'politician'

但是现在我想知道一个政客所属的其他类型。我知道我必须使用group byhaving子句。但我无法提出查询。如何撰写此查询?

2 个答案:

答案 0 :(得分:2)

必须使用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

编辑:避免使用子查询

如果你知道政治家小组的指导,你可以做这样的事情。我没有测试查询,但想法是使用带有映射表的连接过滤 people 表,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

答案 1 :(得分:2)

尝试:

select p.name, t2.type
from types t1
join mapping m1 on m1.guid = t1.guid
join people p on p.wpid = m1.wpid 
join mapping m2 on p.wpid = m2.wpid 
join types t2 on m2.guid = t2.guid
where t1.type = 'politician'
order by 1, 2

- 列出所有政客及其所属的所有类型。

或者,如果您只想要所有政治家的名单和他们所属的不同类型的,请尝试:

select p.name, count(*)
from mapping m1
join people p on p.wpid = m1.wpid 
join mapping m2 on p.wpid = m2.wpid 
where m1.guid = 1 /* replace 1 with appropriate guid for politicians */
group by p.name
order by 1