MySQL计算外键的不同ID

时间:2019-01-26 20:34:29

标签: mysql sql

我有下表:

职位:

-------------------------------------------------------
| id | title | slug | 
-------------------------------------------------------

就业机会

-------------------------------------------------------
| id | job_type| 
-------------------------------------------------------

应用程序:

-------------------------------------------------------
| id | job_opening_id| application_state_id| 
-------------------------------------------------------

application_states

-------------------------------------------------------
| id | name| 
-------------------------------------------------------

我想创建一个查询,该查询对不同的application_state_id进行计数

----------------------------------------------------------------------------
| j.title| j.slug| e.job_type | candidates | hired
----------------------------------------------------------------------------

这是我目前的查询:

SELECT
  j.title,
  j.slug,
  e.job_type,
  count(a1.application_state_id) as candidates,
  count(a2.application_state_id) as hired
FROM
  jobs AS j
INNER JOIN employments AS e ON j.employment_id = e.id
LEFT JOIN applications AS a1 ON a1.job_opening_id = job_openings.id
LEFT JOIN application_states AS as ON as.id = a1.application_state_id
LEFT JOIN applications AS a2 ON a2.job_opening_id = j.id AND a2.application_state_id = 1
GROUP BY 
  a1.application_state_id,
  a2.application_state_id,
  j.id,
  j.title,
  j.slug

我以为我可以创建2个联接并设置application_state_id,但是所有要做的就是计数记录加倍。 我需要在此查询中进行哪些更改?我希望有人能帮助我。

1 个答案:

答案 0 :(得分:1)

您没有提供示例数据,但正如我从您的代码中看到的那样
您要两次加入表applications
因此在1日前获得候选人总数
并在第二名之前获得求职者总数。
我认为您可以放弃第二次加入并进行有条件的计数,以获取聘用候选人的总数。
另外:
select语句必须包含您分组的列和任何聚合的列
而且我不明白为什么需要加入application_states表。
试试这个:

SELECT
  j.title,
  j.slug,
  e.job_type,
  count(a.application_state_id) as candidates,
  sum(case when a.application_state_id = 1 then 1 else 0 end) as hired
FROM 
  jobs AS j INNER JOIN employments AS e ON j.employment_id = e.id
  LEFT JOIN applications AS a ON a.job_opening_id = job_openings.id
GROUP BY 
  j.title,
  j.slug,
  e.job_type