I have four tables that contain some fields
1. user(id, name, email, password, .....)
2. policy1(id, userid, ....)
3. policy2(id, userid, ....)
4. policy3(id, userid, ....)
Now this is clear that user’s primary key (id) is foreign key in other three tables.
I want to fetch total number of tables against each user that contain user id in that table.
for example:
user id 1 has entry in any two tables,
user id 2 has entry in three tables,
user id 3 has entry in any single table
Result should be like
id total
1 2
2 3
3 1
I tried using Left Join but that I could not get the expected result.
You can use a subquery to get the count for each user and then add the values together to get the final result. I am using a
LEFT JOINto return alluserrows even if there is not a matching value in the other tables. If you only want the users with values in the other tables, then you can use anINNER JOIN: