Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

mysql - Get all the rows from the right joined table

I am struggling to get the output in the following format: e.g.

| Total | Roles | Month | Year |
--------------------------------
| 52    | Admin |January| 2012 |
| 0     | Tester|July   | 2012 |
| 41    | HR    |January| 2014 |
| 0     | TL    |June   | 2015 |
| 14    | VP    |March  | 2011 |

I am having two tables (say users and userType), here "type" column in users table is reference to userType table.

I want to get all the rows from right joined table and if there are no values in the left table then it should display "0".

Please view below which I have tried:

SELECT COALESCE(COUNT(u.`userId`),0) AS 'Total',r.`roleName` AS 'Role',COALESCE(MONTH(u.`userOn`),0) AS 'Month', COALESCE(YEAR(u.`userOn`),0) AS 'Year' FROM `users` u RIGHT JOIN `usertype` r ON u.`userRole` = r.`roleId` WHERE YEAR(`userOn`) > 2011 and u.`userRole` = r.`roleId` GROUP by r.`roleName`;

How to get the query for the provided output?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Put your YEAR(userOn) > 2011 condition in ON Clause like below

SELECT COALESCE(COUNT(u.`userId`),0) AS 'Total',r.`roleName` AS 'Role' 
FROM `usertype` r left join `users` u ON u.`userRole` = r.`roleId` 
and YEAR(`userOn`) > 2011
GROUP by r.`roleName`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...