I have the below SQL query:
SELECT
g.name AS gname,
COUNT(u.id) AS noMembers,
f.name AS client,
p.name AS projectName,
g.formed_date AS formedDate
FROM `groups` as g
JOIN users AS u ON u.group_id = g.id
JOIN users AS f ON g.client_id = f.id
JOIN projects AS p ON p.group_id = g.id
What I'm trying to accomplish is this: with a single SQL query to get the name of the current group, the number of members within it (all users are in the same different table, called users), the name of the project the group is currently working on and the client for which the group is working. This has to be done for every group in the grou开发者_运维知识库ps
table.
When I execute the above query it does not return the number of users within the group, but more (not all of the users in the table though) and ONLY 1 row of results, although there are supposed to be more.
COUNT is only going to return one row for the whole selection. What you want to do is use GROUP BY after your JOIN statements.
GROUP BY g.name
This will give you one row for each different group name. It will also only return one result per group name for the client, projectName, and formedDate, so if there are multiple different possibilities for those within each group, you may want to group by multiple columns for more details, for example:
GROUP BY g.name,f.name
精彩评论