Jump to content

Count from Multiple Tables


esport

Recommended Posts

Hi Guys,

I have a table of categories. I want to display all the categories.

 

I also want to display how many times they appear in 2 other tables. I could do 2 more queries to count the number of times they appear, but i was wondering if i could do this in 1 query so I could order them asc and desc by the number of times they appear in other tables.

 

Thanks

 

Daniel

Link to comment
Share on other sites

I haven't tested it, but I think you'd want something along the lines of...

 

SELECT cats.name, COUNT(table1.cat_id) AS count_tabel1, COUNT(table2.cat_id) AS count_table2 FROM cats
JOIN table1 ON table1.cat_id=cats.id
JOIN table2 ON table2.cat_id=cats.id
GROUP BY cats.id

Link to comment
Share on other sites

I managed to work it out. I did sub queries.

eg.

 

SELECT c.id as client_id,
					( SELECT COUNT(p.client_id) 
					FROM projects p
					WHERE p.client_id = c.id
				  ) AS num_projects,
				  ( SELECT COUNT(o.client_id) 
					FROM client_opportunity o
					WHERE o.client_id = c.id
				  ) AS num_opportunities
				  FROM client c

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.