ptamzz
ptamzz

Reputation: 9355

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    |

Upvotes: 1

Views: 2133

Answers (4)

Carsten
Carsten

Reputation: 18446

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;

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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

Upvotes: 2

Elias Hossain
Elias Hossain

Reputation: 4469

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

Upvotes: 0

Marcus
Marcus

Reputation: 12586

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;

Upvotes: 3

Related Questions