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
https://forums.phpfreaks.com/topic/185317-count-from-multiple-tables/
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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.