MYSQL计数跨表的活动

时间:2017-03-04 09:51:25

标签: mysql sql

我有三张桌子:

person
-----------
person_id, active

person_team
-----------
person_id, team_id, active

team
-----------
team_id, active

我希望每个teamsperson的{​​{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

这可以获得团队和个人团队活跃的计数,但不会考虑人是否活跃。我应该使用子查询还是其他类型的连接?

2 个答案:

答案 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