如何编写MySQL Join查询

时间:2011-12-01 09:45:57

标签: mysql database

我有两张桌子。

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       |

两个表中的'uid'都相同。

我想选择所有位于城市“tokyo”的用户,他们也是groupid“16”的组。

所以查询resutl应该是(在这种情况下)

14  | Tokyo    | kawasaki | 1    |

4 个答案:

答案 0 :(得分:3)

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;

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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;

答案 3 :(得分:0)

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