How to write a MySQL Join query

I’ve two tables.

users: 
       uid | city     | username | flag |
       10  | New York | john     | 1    |
       14  | Tokyo    | kawasaki | 1    |
       15  | Tokyo    | coder    | 1    |

groupmember: 
       id  | uid  | groupid  |
       1   | 10   | 16       |
       2   | 14   | 16       |
       3   | 15   | 21       |

The 'uid' in both the tables are the same.

I want to select all users who are in city “tokyo” who are also in the group with groupid “16” .

So the query resutl should be (in this case)

14  | Tokyo    | kawasaki | 1    |

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

SELECT u.uid, u.city, u.username, u.flag 
FROM users u
JOIN groupmember g ON u.uid = g.uid
WHERE u.city = 'Tokyo'
  AND g.groupid = 16;

Method 2

select u.* from users u join groupmember gm on u.uid = gm.uid 
where u.city='Tokyo' and gm.groupid=16

Method 3

SELECT * FROM 
    users INNER JOIN groupmember 
      ON users.uid = groupmember.uid
         AND groupmember.groupid = 16
         AND users.city = 'Tokyo'

Method 4

SELECT u.uid, u.city, u.username, u.flag 
FROM users u, groupmember g 
WHERE u.uid = g.uid 
  AND u.city = 'Tokyo' 
  AND g.groupid = 16;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x