2013-07-09 57 views
1

我有以下查詢其作品...但我需要一些變化:SUM MySQL的

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這是一個SUM我桌上最近的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    

P.S,上面的查詢不會運行

+0

'我如何添加一個限制一個GROUP_CONCAT'你不要在where子句中創建過濾器? – DevZer0

+0

我不明白? – Jimmyt1988

回答

1

你想僅僅是前20個聯賽積分在GROUP_CONCAT每個玩家以及總和?

如果是這樣,也許使用用戶變量: -

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 
+0

如果我得到了所有玩家,然後通過我的玩家在PHP中做了一個循環,並獲得了他們的聯盟數字,那麼這又會如何?難道這比所做的一個查詢更有壓力嗎?這是否合理? – Jimmyt1988

+0

多個查詢通常很慢。上面的查詢應該是相當有效的(雖然沒有測試) – Kickstart

+0

這是比較棘手似乎比:-)相當不錯的查詢,但它不工作尚未;)http://pastebin.com/YYAQPnAw – DanFromGermany