0

I need to create a select query with count from another table.

I have two tables like category and candidates. Every candidate belong to one category.

Here I want to select all categories from category table along with how many candidates available for each category.

like this: category_name(23)

This is how I tried it. but it doesn't work for me.

SELECT c.category_id
         , c.name
         , COUNT(cn.job_category) AS cvs  
FROM job_category c  
LEFT JOIN candidates cn ON cn.job_category = c.category_id
ORDER BY c.name ASC
0

1 Answer 1

2

You are missing the group by clause.

SELECT c.category_id
         , c.name
         , COUNT(cn.job_category) AS cvs  
FROM job_category c  
    LEFT JOIN candidates cn ON cn.job_category = c.category_id
GROUP BY c.category_id
         , c.name
ORDER BY c.name ASC

Note: Without group by, mysql will just return an arbitrary category. It allows this behavior while most other database systems would result in an error when you don't include non-aggregated columns in the group by clause.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.