简体   繁体   English

MySQL:计算多对多表中的实例

[英]MySQL: Counting instances in many-to-many table

I'm creating a small employment site and am wondering if this is possible in MySQL: I have 3 sample jobs and I want to show all users who applied to job_id = 1 who have an application status of 'pending' while showing the total number of other 'pending' and 'pending' + 'hired' applications each user has. 我正在创建一个小型就业网站,我想知道这是否可能在MySQL中:我有3个样本工作,我想向所有申请job_id = 1用户显示申请状态为'pending'同时显示总数每个用户拥有的其他'pending''pending' + 'hired'应用程序。

I've been trying to get my head around this but I'm having problems. 我一直试图解决这个问题,但我遇到了问题。 Is this something MySQL can do? 这是MySQL能做的吗?

users
+----+-------+
| ID |  name |
+----+-------+
|  1 | hanna |
|  2 |   bob |
|  3 |  rick |
+----+-------+

job
+--------+------------+
| job_id |   jobname  |
+--------+------------+
|      1 |    'waiter'|
|      2 |   'janitor'|
|      3 |      'cook'|
+--------+------------+

applications
+----------+---------+-----------+
| user_id  |  job_id |   status  | 
+----------+---------+-----------+
|        1 |       1 | 'pending' |
|        1 |       2 | 'pending' |
|        1 |       3 |  ' hired' |
|        2 |       1 | 'pending' |
|        3 |       1 | 'removed' |
+----------+---------+-----------+

My result set 我的结果集

+--------+---------+-----------+---------------+--------------------+
| job_id | user_id |   status  | count_pending | count_pendinghired |
+--------+---------+-----------+---------------+--------------------+
|      1 |       1 | 'pending' |             2 |                  3 |
|      1 |       2 | 'pending' |             1 |                  1 |
+--------+---------+-----------+---------------+--------------------+

The following query comes close to your suggested output. 以下查询接近您建议的输出。 Note that it doesn't make sense to associate a single job_id with a given user, because a user may have multiple jobs. 请注意,将单个job_id与给定用户相关联是没有意义的,因为用户可能有多个作业。 Likewise, it also doesn't make sense to associate a single status with a given user, since each record represents an aggregation of more than one status. 同样,将单个status与给定用户相关联也没有意义,因为每个记录代表多个状态的聚合。

SELECT user_id,
       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS count_pending,
       SUM(CASE WHEN status = 'pending' OR status = 'hired'
                    THEN 1 ELSE 0 END) AS count_pendinghired
FROM applications
GROUP BY user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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