获取囚犯访客数量

时间:2014-05-14 23:16:31

标签: mysql

表格如下:

Person
first_name
middle_name
last_name
person_ssn

Prisoner
person_ssn
prisoner_id

Visitation
visitor_id
prisoner_id

visitor
visitor_id
first_name
last_name

我有兴趣获得一个囚犯的名字和他们有多少访客。

到目前为止我得到了什么:

select person.first_name, person.middle_name, person.last_name, count(visitor_id) AS visitorCount
from prisoner
inner join person on prisoner.person_ssn = person.person_ssn
inner join visitation on prisoner.prisoner_id = visitation.prisoner_id;

这似乎只会导致一个囚犯

1 个答案:

答案 0 :(得分:1)

您需要group by条款。否则,您的查询是一个返回一行的聚合查询。

select person.first_name, person.middle_name, person.last_name, count(visitor_id) AS visitorCount
from prisoner
inner join person on prisoner.person_ssn = person.person_ssn
inner join visitation on prisoner.prisoner_id = visitation.prisoner_id
group by person.first_name, person.middle_name, person.last_name;