Reputation: 89
I've got an issue I have 3 tables:
1 table named "members" (it has the members data, ID, Username, Password)
2 table named "schools" (it has list of schools ID, School_Name, School_Number)
3 table named "members_schools" (Here I two columns: User_ID, School_ID)
so I'm in a middle of a mess, I need to realize a sorting or grouping system for example: School Of St.Peter, Number 8, has an ID 1 in "schools" table
users have the right to choose ,from a list, this school and then I made a query to save their choice in "members_schools" something like:
User_ID :: Scool_ID
4 :: 1
This should bring back that: the user with ID:4 is attending the school with ID:1 which is here "School Of St.Peter"
now I tried to LEFT JOIN the tables among each others, but so far no luck!! I'm confused how to realize this thing, retrieving the data from the three tables and show them on a page in this order.
School :: No. Attenders
School Of St.Peter :: "NUMBER OF MEMBERS WHO HAVE APPLIED FOR THIS SCHOOL"
Thank you guys.
Upvotes: 0
Views: 85
Reputation: 4166
You don't need to use three tables until details of all users is required. To get a count we need to use only schools
and member_schools
table.
Use LEFT JOIN
and then count the user_id in result
SELECT schools.School_Name AS School, IFNULL(COUNT(member_schools.User_ID),0) AS Number_of_Attenders
FROM schools LEFT JOIN member_schools
ON schools.ID = member_schools.School_ID
GROUP BY schools.School_name
Sample Output
School :: Number_of_Attenders
School Of St.Peter :: 4
To show username of all members, use GROUP_CONCAT
SELECT schools.School_Name AS School, GROUP_CONCAT(members.Username) AS Attenders
FROM schools LEFT JOIN member_schools
ON schools.ID = member_schools.School_ID
INNER JOIN members
ON member_schools.User_ID = members.ID
GROUP BY schools.School_name
Sample Output
School :: Attenders
School Of St.Peter :: Isaac, Kevin, Rockse, Aish
Upvotes: 1
Reputation: 3733
SELECT schools.School_name AS `School`, COUNT(0) AS `Nr. Attenders`
FROM schools INNER JOIN members_schools ON schools.id = members_schools.School_ID
GROUP BY schools.School_name
Would give you the nr of members per school The members table is not relevant for the number of attenders.
Upvotes: 1