简体   繁体   中英

MySQL return values count

I have a fairly boggling problem. What I'm after is a list of all the industries whether they have been linked to a job or not. So..

Web Design [0]
Accounts[3]
Sales[1]
Marketing[0]

So that the jobs in the database have a industry id that's saved with the job. the industry table has a list of industry types. Web Design, Accounts, Sales, Marketing etc Below is my SQL so far

SELECT ind.name,ind.id, GROUP_CONCAT(job.industry_id) AS id,
COUNT(*) AS industry_count
FROM jobs AS job,
industries AS ind
WHERE ind.id = job.industry_id
GROUP BY industry_id

This returns the count of each job that belongs to an industry but i want all industries to be returned with or without jobs linked to them. Thank you all so much for helping. Rob

It seems you need a LEFT JOIN . Try this out:

SELECT ind.name, ind.id,
  COALESCE(GROUP_CONCAT(job.industry_id), 'default_value') AS id,
  COUNT(job.industry_id) AS industry_count
FROM industries ind
LEFT JOIN jobs job ON ind.id = job.industry_id
GROUP BY ind.id

Note if there is no job for a given industry you'll get null in the GROUP_CONCAT. You can add a default value for those cases that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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