1

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

我有一个包含球员的梦幻足球统计数据。为简化起见,在这种情况下,我使用了 3 列:玩家、积分、年份。

我希望运行一个查询,以返回 2010 年和 2011 年均进入前 50 名(基于积分)的球员列表。

我已经在使用子查询、在一张表上进行连接等方面进行了很多搜索,但我仍然对如何处理这个问题感到茫然。

4

4 回答 4

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
于 2012-09-13T16:08:05.013 回答
0

您可以使用 a 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
);
于 2012-09-13T16:40:32.897 回答
0

Here is an example. I assumed that you calculate top50 based on sum of points and you have several entries for each player in each year.


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
于 2012-09-13T16:36:15.663 回答
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
    
于 2012-09-13T16:57:18.950 回答