Mysql返回子查询中的匹配用户

时间:2012-09-13 16:04:12

标签: mysql

我正在寻找一种方法来编写一个查询来比较多个mysql子查询的结果,并返回每个查询中的用户。

我有一个包含玩家幻想足球统计数据。为了简化,在这种情况下,我使用了3列:播放器,点,年。

我希望运行一个查询,返回2010年和2011年排名前50位(基于积分)的玩家列表。

我在搜索子查询,在一张桌子上进行连接等方面做了大量的搜索,但是我仍然不知道如何处理它。

4 个答案:

答案 0 :(得分:0)

您可以这样做:

SELECT  a.player

FROM    (SELECT player FROM players WHERE Year = 2010 ORDER BY points DESC LIMIT 50) a

        JOIN

        (SELECT player FROM players WHERE Year = 2011 ORDER BY points DESC LIMIT 50) b
        ON a.player = b.player

答案 1 :(得分:0)

这是一个例子。我假设您根据积分总和计算top50,并且每年每位玩家都有几个参赛作品。


select y2010.player 
from (
  select player, sum from (
    select st1.player player, sum(st1.points) sum from stats st1 where st1.year = 2010 group by st1.player order by sum desc
  ) t1 limit 50 offset 0
) y2010, (
  select player, sum from (
    select st1.player player, sum(st1.points) sum from stats st1 where st1.year = 2011 group by st1.player order by sum desc
  ) t1 limit 50 offset 0
) y2011
where y2010.player = y2011.player

答案 2 :(得分:0)

您可以使用UNION ALL,这会在两年内获得Top 50并将它们放在相同的结果集中,不需要加入:

(
    select player, year, points 
    from players
    where year = 2010
    order by points desc
    limit 50
)
union all
(
    select player, year, points 
    from players
    where year = 2011
    order by points desc
    limit 50
);

答案 3 :(得分:0)

您是否想要:

,这有点模棱两可
  • 2010年进入前50名的所有球员,以及2011年进入前50名的所有球员:

    SELECT *
    FROM   scores
    WHERE  year = 2010
       AND points >= (SELECT MIN(points) FROM (
                       SELECT   points
                       FROM     scores
                       WHERE    year = 2010
                       ORDER BY points DESC
                       LIMIT    50
                     ) t)
    UNION ALL
    SELECT *
    FROM   scores
    WHERE  year = 2011
       AND points >= (SELECT MIN(points) FROM (
                       SELECT   points
                       FROM     scores
                       WHERE    year = 2011
                       ORDER BY points DESC
                       LIMIT    50
                     ) t)
    
  • 所有在 2010年和2011年都进入前50名的玩家,在这种情况下,您需要进一步对结果进行分组:

    SELECT   player
    FROM     (
               -- query as above
             ) t
    GROUP BY player
    HAVING   COUNT(DISTINCT year) = 2