Mysql查询在同一个表中选择

时间:2014-12-23 23:03:02

标签: mysql select

我有桌子人

Name               |       Score    |   Date

Don                |         A      |   12-10-2014              
Don                |         B      |   12-10-2014           
Mary               |         A      |   12-10-2014
Mary               |         C      |   12-10-2014
Mary               |         D      |   12-10-2014
Jack               |         A      |   12-10-2014
Jack               |         B      |   12-10-2014
Jack               |         C      |   12-10-2014

我想获得得分A和B 的人的记录。

Mary | A | 12-10-2014

将不会出现在结果中,因为她没有得分B.结果必须同时包含AB

所以输出应该如下。玛丽不应该在结果中,因为她只有得分A

Name               |       Score    |   Date

Don                |         A      |   12-10-2014              
Don                |         B      |   12-10-2014          
Jack               |         A      |   12-10-2014
Jack               |         B      |   12-10-2014

我尝试过以下查询,但结果不对。

 select * 
 from people 
 where score='B' and Name in (select Name 
                              from people 
                              where score='A' 
                              group by Name)

4 个答案:

答案 0 :(得分:1)

您可以进行自我加入,如下所示:

SELECT * FROM people p1 JOIN people p2 ON p1.name = p2.name WHERE p1.score = 'A' and p2.score = 'B'

答案 1 :(得分:1)

此子查询为您提供名称值列表,其中至少有一个A分数和一个B分析。

SELECT DISTINCT a.Name 
  FROM people AS a
  JOIN people AS b ON a.Name = b.Name AND a.score='A' AND b.score = 'B'

然后,您可以加入子查询以提取所需的记录。

SELECT people.Name, people.Score, people.Date
  FROM people
  JOIN (
        SELECT DISTINCT a.Name 
          FROM people AS a
          JOIN people AS b ON a.Name = b.Name AND a.score='A' AND b.score = 'B'
       ) ab ON ab.Name = people.Name
 WHERE Score IN ('A','B')

答案 2 :(得分:1)

我认为两个exists条款可能是最合乎逻辑的方法:

select p.*
from people p
where score in ('A', 'B') and
      exists (select 1 from people p2 where p2.name = p.name and p2.score = 'A') and
      exists (select 1 from people p2 where p2.name = p.name and p2.score = 'B');

答案 3 :(得分:0)

使用别名会降低复杂性,而且比使用表名更容易。 这是更新的一个加入子查询,从@ Olie的回答中提取所需的记录作为扩展和更新的答案:

 SELECT P.Name AS Name, P.Score AS Score, P.Date AS Date
  FROM people P
  JOIN (
        SELECT DISTINCT P1.Name 
          FROM people P1
          JOIN people P2 ON P1.Name = P2.Name AND P1.score='A' AND P2.score = 'B'
       ) P3 ON P3.Name = P.Name
 WHERE P.Score IN ('A','B')