1

我有以下有效的查询......但我需要一些更改:

SELECT
    p.pid,
    p.name,   
    GROUP_CONCAT( gC.leaguepoints ORDER BY leaguepoints DESC ) AS leaguepoints        
FROM
    golf_player p
LEFT JOIN
    golf_card gC ON
    p.pid = gC.pid
GROUP BY
    p.pid
ORDER BY
    p.name
DESC

我真正想要的是返回另一个名为 totalleaguepoints 的属性,它是我表中最近 20 个联赛积分的总和。

如何向 group_concat 添加限制?

可能是这样的?

 SELECT                
      p.pid,
      p.name,   
      GROUP_CONCAT( gC.leaguepoints ORDER BY leaguepoints DESC ) AS leaguepoints, 
      SUM(  
        SELECT 
          gC2.leaguepoints
        FROM
          golf_card gC2
        WHERE 
          gC2.pid = p.pid
        ORDER BY
          leaguepoints
          DESC
        LIMIT 20           
      ) AS totalleaguepoints
  FROM
    golf_player p
  LEFT JOIN
    golf_card gC ON
    p.pid = gC.pid
  GROUP BY
    p.pid
  ORDER BY
    p.name
    DESC               

PS,上面的查询没有运行

4

1 回答 1

1

您是否只想要 group_concat 中每位球员的前 20 名联赛积分以及总和?

如果是这样,可以使用用户变量:-

SELECT                
    p.pid,
    p.name,   
    GROUP_CONCAT( gC.leaguepoints ORDER BY leaguepoints DESC ) AS leaguepoints, 
    SUM(gC.leaguepoints) AS totalleaguepoints
FROM golf_player p
LEFT JOIN 
(
    SELECT pid, leaguepoints, @Sequence:=IF(@PrevPid = pid, @Sequence + 1, 0) AS aSequence, @PrevPid := pid
    FROM
    (
        SELECT pid, leaguepoints
        FROM golf_card 
        ORDER BY pid, leaguepoints DESC
    ) Sub1
    CROSS JOIN (SELECT @PrevPid := 0, @Sequence := 0) Sub2
) gC
ON p.pid = gC.pid AND aSequence < 20
GROUP BY p.pid
ORDER BY p.name DESC 
于 2013-07-09T10:22:48.947 回答