如何在一个

时间:2016-12-20 05:31:35

标签: sql sqlite

我有表用户参与者聊天。我需要通过聊天名称让特定聊天中的所有用户和聊天用户聊天。例如当前表:

  user      chat          participant
id|name   id|name       user_id|chat_id
1|Mike    1|School            1|1
2|John    2|Football          2|1
3|Sara    3|Gym               1|2
                              3|3

通过关键字"学校"我想得到这个

Mike|2
John|1

我有两个查询可以获得结果中的第一列和第二列,但不知道如何合并它:

SELECT user.name FROM user 
JOIN participant ON (user.id = participant.user_id) 
JOIN chat ON (participant.chat_id = chat.id) WHERE chat.name = 'School';

那给了我

Mike
John

SELECT user.name, COUNT(*) FROM user 
JOIN participant ON (user.id = participant.user_id) GROUP BY user.name;

返回

John|1
Mike|2
Sara|1

那么如何组合呢?

2 个答案:

答案 0 :(得分:1)

使用子查询和连接:

            select u.name,count(p.chat_id) as 'Count' from user u
            inner join participant p on p.user_id = u.id
            where 
            p.user_id  in ( select user_id from participant pp inner join chat cc on cc.id = pp.chat_id  where 
            cc.name = 'School' )    
            group by u.name
            order by Count desc
  

输出:

enter image description here

答案 1 :(得分:1)

尝试

SELECT p1.name, COUNT(p.user_id) totUser
FROM participant p 
INNER JOIN (select u.id, u.name FROM participant p 
    inner JOIN chat c ON c.id = p.[chat_id]
    INNER JOIN user u ON u.id = p.user_id
    AND c.name = 'School') p1 ON p1.id = p.user_id
GROUP BY p1.name