我有 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 by
和 having
子句。但我无法提出查询。如何写这个查询?
最佳答案
尝试:
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
关于sql - 在 Postgresql 中使用 group by 子句和多个内部联接选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344732/