For following tables, I’d like to select all users and their groups for a specific account.
USERS
-id
-name
-groupid
-accountid
GROUPS
-id
-name
-accountid
I’m doing the following:
SELECT
USERS.ID,
USERS.NAME,
GROUPS.ID,
GROUPS.NAME,
FROM GROUPS JOIN USERS ON USERS.ACCOUNTID= GROUPS.ACCOUNTID
WHERE GROUPS.ACCOUNTID=1
For some reason results are repeated 3 times(which is the number of group). Each user is displayed 3 times with different GROUPID.
update If I join on GROUPID instead, like it was suggested. I get the following. As you can see only a single user is displayed per group even though there are more than one user in a group.
USER_ID GROUP_ID GROUP_NAME NAME
42 6 Teacher John E.
59 8 Student Bill W.
Each User is displayed 3 times with different GROUPID due to you join on the ACCOUNTID instead of GROUPID.
You could try the below ie join on the GROUPID.
UPDATED:
http://sqlfiddle.com/#!2/3afee/1