Search code examples
sqlflaskcount

One SQL count query


I have made 4 separate queries mainly for counting. It works, but it would be much simpler both in sql and later in flask/jinja to have one query. Is this achievable?

        SELECT users.id AS id,
        registration_date,
        login
        FROM users
        ORDER BY id;


        SELECT users.id AS id,
        count(question.id) as question_number
        FROM users
        INNER JOIN question ON question.user_id = users.id
        GROUP BY users.id
        ORDER BY id;


        SELECT users.id AS id,
        count(answer.id) as answer_number
        FROM users
        INNER JOIN  answer ON answer.user_id = users.id
        GROUP BY users.id
        ORDER BY id;


        SELECT users.id AS id,
        count(comment.id) as comment_number
        FROM users
        INNER JOIN comment ON comment.user_id = users.id
        GROUP BY users.id
        ORDER BY id;

I tried this (of course with no success):

        SELECT users.id AS id,
        registration_date,
        login
        count(question.id) as question_number
        count(answer.id) as answer_number,
        count(comment.id) as comment_number
        FROM users
        INNER JOIN question ON question.user_id = users.id
        INNER JOIN answer ON answer.user_id = users.id
        INNER JOIN comment ON comment.user_id = users.id
        GROUP BY users.id, registration_date, login 
        ORDER BY id

Solution

  • SELECT 
        u.id AS id,
        u.registration_date,
        u.login,
        q.question_number,
        a.answer_number,
        c.comment_number
    FROM 
        users u
    LEFT JOIN 
        (SELECT user_id, COUNT(1) AS question_number 
         FROM question 
         GROUP BY user_id) q ON q.user_id = u.id
    LEFT JOIN 
        (SELECT user_id, COUNT(1) AS answer_number 
         FROM answer 
         GROUP BY user_id) a ON a.user_id = u.id
    LEFT JOIN 
        (SELECT user_id, COUNT(1) AS comment_number 
         FROM comment 
         GROUP BY user_id) c ON c.user_id = u.id
    ORDER BY 
        u.id;