我有三张桌子:
person
-----------
person_id, active
person_team
-----------
person_id, team_id, active
team
-----------
team_id, active
我希望每个teams
中person
的{{1}}得到active
的计数。
到目前为止,我有:
SELECT t.id, t.title, t.created_timestamp, COUNT(p_t.tag_id) AS count
FROM team t
LEFT JOIN
person_team p_t ON p_t.team_id = t.id AND p_t.active = 1
WHERE
t.active = 1
GROUP BY t.id
ORDER BY t.title
这可以获得团队和个人团队活跃的计数,但不会考虑人是否活跃。我应该使用子查询还是其他类型的连接?
答案 0 :(得分:1)
您需要在联接中添加result
表,并从该表中计算一列:
person
答案 1 :(得分:1)
您应该在子选择中使用内部联接以获取不在
组中的列select k.id, t.title, t.created_timestamp, k.count from
( SELECT t.id COUNT(p_t.tag_id) AS count
FROM team t
LEFT JOIN
person_team p_t ON p_t.team_id = t.id AND p_t.active = 1
WHERE
t.active = 1
GROUP BY t.id ) k
inner join team t on t.id = k.id