【问题标题】:What's the proper way to exclude this group from my MySQL Query?从我的 MySQL 查询中排除该组的正确方法是什么?
【发布时间】:2012-07-19 00:39:45
【问题描述】:

表 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 团队的人。

我的第一次尝试是:

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

问题是因为乔是教练,他符合标准~尽管他也已经是一名球员了。

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

【问题讨论】:

    标签: mysql join


    【解决方案1】:

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

    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。

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

    【讨论】:

    • 谢谢!这正是我想要的。
    【解决方案2】:
    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')
    

    【讨论】:

    • +1 谢谢,研究了你的答案,我了解到为什么EXISTS 方法比其他样式的NOT IN 子查询更有效。
    【解决方案3】:

    您可能可以这样做:

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

    【讨论】:

      【解决方案4】:
      SELECT profile_id
      FROM users
      WHERE profile_id NOT IN (
          SELECT profile_id
          FROM user_role_to_team_lookup
          WHERE role = 'player');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-01
        • 2015-09-27
        • 1970-01-01
        相关资源
        最近更新 更多