1

I have three related tables users, groups and group_members. The users table contains users information and groups table contains the group name and group owner id (ie, users_id). Table group_members contains the members of each groups (user_id and group_id). I tried to load the users details of each group but the result is not correct. My tables are,

users


id   firstname   lastname    email

1    anu         mm          [email protected]
2    manu        mohan       [email protected]
3    cinu        ab          [email protected]
4    vinu        mj          [email protected]
5    vijesh      cc          [email protected]
6    admin       admin       [email protected]

groups


id     user_id     name

1      1           group1
2      2           group2
3      2           group3
4      3           group4

group_members


id    user_id    group_id

1     1          1
2     2          2
3     2          3
4     3          4
5     2          3
7     1          2
8     1          3
9     3          1

But when I tried the bellow query,

select users.firstname,users.lastname,users.email,groups.name as groupname from users inner join groups on groups.user_id = users.id inner join group_members on group_members.group_id = groups.id where groups.id=3 AND users.firstname LIKE 'cin%' OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%'

getting the result (which is not expected)


firstname     lastname      email            groupname

cinu          ab            [email protected]   group4

In this case I used the where condition WHERE groups.id =3 but the result takes the group4 (groups.id is 4). Please suggest me a solution.

1
  • Note that group_members.id is redundant Commented Mar 23, 2015 at 7:49

1 Answer 1

2

your have to use () arround your or statements:

 where groups.id=3 AND (users.firstname LIKE 'cin%' OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%')

Because AND has a higher priority you query looks like:

 where (groups.id=3 AND users.firstname LIKE 'cin%') OR users.lastname LIKE 'cin%' OR users.email LIKE 'cin%'

And that is not what you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.