SQL查询计数3个表中的条目

时间:2011-06-17 00:43:43

标签: sql aggregate-functions

我有一个包含3个表的SQL数据库:

table1:user

id | nickname
1    peter
2    tom

表2:帖子

user_id | title | text
1         hmmm    bla
1         yeah    blub
2         blub    dada
1         yuhu    asdf

表3:消息

user_id | title | message
1         hello   bla
2         hi      blub
2         hey     dada
2         huhu    asdf

如何在一个查询中为每个用户的帖子/消息计算每个条目?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT a.user_id, 
       COALESCE(b.cnt_b, 0) posts_count, 
       COALESCE(c.cnt_c, 0) messages_count
  FROM user a LEFT JOIN 
            (
                SELECT user_id, COUNT(1) cnt_b
                    FROM posts b 
                 GROUP BY user_id
            ) b
     ON a.user_id = b.user_id LEFT JOIN
            (
                SELECT user_id, COUNT(1) cnt_c
                    FROM messages c 
                 GROUP BY user_id
            ) c
    ON a.user_id = c.user_id