从MySQL查询中排除这个组的正确方法是什么?

时间:2012-02-03 18:40:22

标签: mysql join

表1:用户

| profile_id | name    |
------------------------
| 1          | Joe     |
| 2          | Jane    |
| 3          | Jill    |
| 4          | Jeffery |

表2:团队查找的用户和角色

| team_id | profile_id | role   |
---------------------------------
| 1       | 1          | coach  |
| 1       | 2          | player |
| 2       | 4          | coach  |
| 2       | 1          | player |

情节是Jill正在建立一个团队,而且限制是你不能成为一个以上团队的玩家。因此,我正在尝试构建一个查询,以提升那些有资格加入Jill团队的人。

我的第一次尝试是:

SELECT `users`.`profile_id`
FROM `users` LEFT JOIN `user_role_to_team_lookup` AS `utr` USING(`profile_id`)
WHERE `utr`.`role` != 'player' OR `utr`.`role` IS NULL

问题在于,因为乔是一名教练,所以即使他已经是一名球员,他也符合标准〜

从结果集中排除已经是玩家的用户的正确方法是什么?

4 个答案:

答案 0 :(得分:2)

我会在没有大多数人使用的子查询的情况下写这个:

SELECT u.profile_id
FROM users AS u 
LEFT OUTER JOIN user_role_to_team_lookup AS utr 
  ON u.profile_id = utr.profile_id AND utr.role = 'player'
WHERE utr.profile_id IS NULL

换句话说,寻找已经是玩家的用户。那些不是玩家的人将不会在外部联接中匹配任何行,因此任何utr列都将为NULL。

但最好将条件放在连接的ON子句中。

答案 1 :(得分:1)

SELECT u.profile_id
    FROM users u
    WHERE NOT EXISTS(SELECT 1
                         FROM user_role_to_team_lookup urtl
                         WHERE urtl.profile_id = u.profile_id
                             AND urtl.role = 'player')

答案 2 :(得分:0)

您可以这样做:

SELECT profile_id FROM users
WHERE profile_id NOT IN (SELECT DISTINCT profile_id FROM utr WHERE role = 'player');

答案 3 :(得分:0)

SELECT profile_id
FROM users
WHERE profile_id NOT IN (
    SELECT profile_id
    FROM user_role_to_team_lookup
    WHERE role = 'player');