SQL - 如果其中一个ID具有某个列值,则选择所有匹配的ID

时间:2012-05-30 22:06:07

标签: mysql sql

我不确定如何说出这个问题,但更容易解释。

如果我有一个看起来像这样的表:

+-------+----------+-------+
| User  | Result   | Level |
+-------+----------+-------+
|    1  | Victory  |     1 |
|    1  | Victory  |     2 |
|    1  | Victory  |     3 |
|    2  | Victory  |     1 |
|    2  | Defeat   |     2 |
|    3  | Defeat   |     1 |
|    4  | Defeat   |     1 |
|    5  | Defeat   |     1 |
+-------+----------+-------+

我希望只能选择在第3级获胜的用户。因此,选择将返回:

+-------+----------+-------+
| User  | Result   | Level |
+-------+----------+-------+
|    1  | Victory  |     1 |
|    1  | Victory  |     2 |
|    1  | Victory  |     3 |
+-------+----------+-------+

其他人不会被退回,因为他们没有完成3级。

非常感谢!我希望我能清楚地解释清楚。

2 个答案:

答案 0 :(得分:5)

如果您只是想知道哪些用户在第3级获胜:

SELECT User FROM my_table WHERE Result = 'Victory' AND Level = 3

但是,如果(如您所示)您想要所有这些用户的结果(感谢@Andomar和@ConradFrix在下面的评论):

SELECT DISTINCT m1.*
FROM   my_table AS m1
  JOIN my_table AS m2 USING (User)
WHERE  m2.Result = 'Victory'
   AND m2.Level  = 3

答案 1 :(得分:3)

您可以使用exists子句,例如:

select  *
from    scores s
where   exists
        (
        select  *
        from    scores vl3
        where   vl3.user = s.user
                and vl3.Result = 'Victory'
                and vl3.Level >= 3
        )