Skip to content

Instantly share code, notes, and snippets.

@mattm

mattm/solution.sql

Created Nov 1, 2017
Embed
What would you like to do?
SELECT
users.user_id,
COALESCE(post_count, 0) AS post_count,
COALESCE(page_count, 0) AS page_count
FROM users
LEFT JOIN (
SELECT user_id, COUNT(*) AS post_count
FROM posts
GROUP BY user_id
) post_counts ON post_counts.user_id = users.user_id
LEFT JOIN (
SELECT user_id, COUNT(*) AS page_count
FROM pages
GROUP BY user_id
) page_counts ON page_counts.user_id = users.user_id
+---------+------------+------------+
| user_id | post_count | page_count |
+---------+------------+------------+
| 1 | 3 | 0 |
| 2 | 2 | 2 |
| 3 | 0 | 5 |
+---------+------------+------------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.