简体   繁体   中英

MySql count from other table as join and add to every row of results

Got a small MySql problem I was hoping someone could take a look at.

Current Sql:

SELECT IFNULL(ua.total, 0) applications, 
       users_applications.job_id as job_id, 
       users.* 
FROM users_applications 
        LEFT OUTER JOIN users 
             on (users_applications.user_id = users.id) 
        LEFT OUTER JOIN ( 
                           SELECT COUNT(*) total, job_id, id 
                           FROM users_applications
                           GROUP BY job_id ) AS ua 
                  ON (users_applications.id = ua.id)

Which is great and it's returning something like:

applications  |  job_id  |  user_id  |
-------------------------------
3     |   1001    |   1001  |
0     |   1001    |   1002  |
0     |   1001    |   1003  |
1     |   1003    |   1004  |
1     |   1003    |   1005  |
0     |   1004    |   1006  |

Although it is counting the number of applications for that job it's only doing it for the first row, I'd like it to appear in every row instead of just a 0 for subsequent rows as it is at the moment.

Many thanks

Try this one.

SELECT  c.totalCount,
        a.job_id,
        a.user_id
FROM    users_applications a
            LEFT JOIN users b
                ON a.user_ID = b.ID
            LEFT JOIN
                (
                    SELECT job_ID, count(*) totalCount
                    FROM user_applications
                    GROUP BY job_ID
                ) c on a.job_ID = c.jobID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM