Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

omrakhurs's avatar

How to make two inner joins with a count in them?

I have three tables:

  1. Users (id, dept_id)
  2. Departments (id, deptStringName)
  3. Absences (id, user_id)

I am trying to figure out Absences per Department. I know I need two inner joins, but at the moment I am confused about how to insert a count in two inner joins using the Laravel Query Builder syntax.

The eventual result could be like:

+-------+---+
| DeptA | 3 |
| DeptF | 7 |
| DeptH | 3 |
| DeptT | 7 |
| DeptZ | 5 |
+-------+---+
0 likes
3 replies
abusalameh's avatar
Level 30

let's try this query


SELECT COUNT(abs.id) as AbsenceCount , dept.deptStringName
FROM Absences abs  
JOIN Users u on u.id = abs.user_id
JOIN Departments dept on dept.id= u.dept_id
group by dept.deptStringName

omrakhurs's avatar

This works, thank you! Could you please explain it?

abusalameh's avatar

ok @omrakhurs

1- you have three tables - absences , departments , users linked via foreign keys

2- we start from the absences because we have user_id

3- we join it with users

4- we join the users with departments because we have dept_id in the users table

5- we group them by departmentName after selecting the count of each absence per department.

1 like

Please or to participate in this conversation.