3

我有 3 个具有以下定义的表格

people
------
- wid 
- name

types
-----
- guid
- type

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

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 byandhaving子句。但我无法提出查询。如何编写这个查询?

4

2 回答 2

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

编辑:避免 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
于 2012-11-12T13:45:29.393 回答
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
于 2012-11-12T14:01:37.680 回答