How can i show the total number of staff in each offices that both stored in my database in php?

Okay so in my website I have shown my two tables which are Office Table and Staff Table together so it looks like this

table

Now i am trying to also show the total number of Staffs and I am struggling to do it. This is my query for the the Office and Staff table. How and What can i add to also show the total number of staff in each office?

SELECT * FROM offices           
JOIN staffs             
ON offices.office_id = staffs.st_office_id;

I hope someone can help me.

Upvotes: 0

Views: 56

Answers (2)

Roger Cracel
Roger Cracel

Reputation: 151

So you have two table: offices and staffs and you want to count all staff across all offices?

SELECT COUNT( 1 )
  FROM offices
  JOIN staffs ON( offices.office_id = staffs.office_id );

If you want the count per office, you can:

SELECT offices.office_id, offices.name, COUNT( 1 )
  FROM offices
  JOIN staffs ON( offices.office_id = staffs.office_id )
 GROUP BY offices.office_id, offices.name;

Hope this helps!

Upvotes: 1

Max Huzmiev
Max Huzmiev

Reputation: 61

It might be look as:

select 
  a.office_name, 
  (select count(*) from staffs b where b.st_office_id = a.office_id)
from offices a

Upvotes: 0

Related Questions