MySql从另一个表计数为连接并添加到每行结果

时间:2012-08-15 16:30:42

标签: mysql join count

得到一个小的MySql问题我希望有人可以看看。

当前的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)

哪个很好,它会返回类似的内容:

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

虽然它正在计算该作业的应用程序数量,但它只是在第一行中执行它,我希望它出现在每一行而不是仅仅为后续行的0,就像现在一样。

非常感谢

1 个答案:

答案 0 :(得分:2)

试试这个。

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