I have two tables:
User : (id, username, created_at, updated_at)
Comment : (comment_id, user_id, username, created_at, updated_at)
Note: yes, I do understand Comment table has a duplicated field, 'username'. However, the table is already designed in that way and I have no permission to redesign the schema.
And this is an output format how I want to extract data from tables.
id | username | num_of_counts
And this is two different sql codes I've tried with (I've simplified the codes to show you what I'm trying to do... minor typos may exist but general ideas are here.)
-- Ver 1
SELECT u.id, u.username, COUNT(c.id)
FROM User u
LEFT JOIN Comment c ON u.id = c.id
GROUP BY u.id
-- Ver 2
SELECT u.id, u.username, c.cnt
FROM User u
LEFT JOIN (SELECT id, COUNT(*) AS cnt
FROM Comment
GROUP BY user_id) c
ON u.id = c.id
GROUP BY u.id
Both codes gives me the same issue:
"Column 'username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
After reading some articles regarding it, I've learned that there's a conflict between selecting 'username' and grouping rows by 'id'.
I'm still googling and reading similar cases but still getting the same issue (I'm not that good at sql stuff...)
What would be the best way to code sql query to get outputs in this format?
id | username | num_of_comments
1 | Tyler | 3
2 | Jane | 5
3 | Jack | 1