Mysql how to do this query -


select u.username, count(t.tid) total tbl2 t join users u on t.userid = u.userid group t.userid 

the above query works fine , all, returns number of total task each user has atleast 1 task in tbl2 table.

but want return users, if user doesn't have records associated him in second tbl2 table. want total show 0 users doesn't have records, how can accomplish this?

the problem other answers given want select users have no associated records; using left join, users table on wrong (nullable) side of join. replace left join right join, syntax feels unintuitive me.

the standard answer reverse order of tables while using left join:

select u.username, count(t.tid) total users u left join tbl2 t on t.userid = u.userid group u.username 

note it's better practice (and, in dbmses, required) group on non-aggregated columns in select list, rather grouping on userid , selecting username.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -