MySQL: How to count rows when multiple joined tables ?? +Query: SELECT p.role FROM users u INNER JOIN roles r ON r.id=u.role INNER JOIN permissions p ON p.role=r.id WHERE p.p_id=19 AND p.p_update=1 AND r.active=1 GROUP BY p.role +Result: ________ |p_role:| |_______| | 1 | | 4 | |_______| When I add COUNT() function to p.role: +Query: SELECT COUNT(p.role) FROM users u INNER JOIN roles r ON r.id=u.role INNER JOIN permissions p ON p.role=r.id WHERE p.p_id=19 AND p.p_update=1 AND r.active=1 GROUP BY p.role +Result: _______________ |COUNT(p_role):| |______________| | 5 | | 1 | |______________| Why I see 2 records I already use COUNT() function?? I don't want to see result like this. I want to count rows of query above. I want to see result like this: _______________ |COUNT(p_role):| |______________| | 2 | |______________| Please anyone help me. Thanks in advance! Sorry for my broken English.
答案 0 :(得分:1)
由于查询中包含GROUP BY
子句,它会返回每p.role
个值的计数。如果您希望查询返回一个值,则可以删除GROUP BY
,例如:
SELECT COUNT(DISTINCT(p.role)) FROM users u
INNER JOIN roles r ON r.id=u.role
INNER JOIN permissions p ON p.role=r.id
WHERE p.p_id=19 AND p.p_update=1 AND r.active=1;
顺便说一句,我已将DISTINCT
添加到查询中,以便它返回不同p.role
值的计数。如果您只想记录记录,可以删除DISTINCT
。