Skip to content
Advertisement

Mysql count the different id’s of the foreign key

I have the following tables:

jobs:

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

employments:

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

applications:

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

application_states

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

I want to create a query that counts the different application_state_id’s

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

This is the query that i have at the moment:

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

I thought i could create 2 joins and set the application_state_id, but all that does is count records double. What do i need to change in this query? I hope someone can help me.

Advertisement

Answer

You did not provide sample data, but as I see from your code
you are joining the table applications twice,
so by the 1st to get the total number of candidates
and by the 2nd to get the total number of hired candidates.
I think you can drop the 2nd join and do conditional counting to get the total number of hired candidates.
Also:
the select statement must include the columns that you group by and any aggregated columns
and I don’t see why you need to join to the application_states table.
Try this:

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement