2015-06-19 56 views
0

在下面的查詢在不同的表中的列:算術與MySQL的[optmization]

SELECT 
    (SELECT nick FROM nicks n WHERE n.pid=p.id LIMIT 1 ORDER BY id DESC) as nick 
    , (
      (
      (SELECT COUNT(*) FROM kills k WHERE k.pid = p.id) 
      + 
      (SELECT COUNT(*) FROM votos v WHERE v.pid = p.id) 
      ) 
      - (SELECT COUNT(*) FROM deaths d WHERE d.pid = p.id) 
) as score 
    , (SELECT COUNT(*) FROM kills k WHERE k.pid = p.id) as kills 
    , (SELECT COUNT(*) FROM deaths d WHERE d.pid = p.id) as deaths 
    , (SELECT COUNT(*) FROM headshots h WHERE h.pid = p.id) as headshots 
    , (SELECT COUNT(*) FROM votos v WHERE v.pid = p.id) as reputation 
FROM players p 
WHERE p.uuid='STEAM_x:x:xxxxxx' 
GROUP BY kills 

此查詢工作正常...但我認爲存在着一個更好的方式來做到這一點。 任何人都可以幫助我優化此查詢嗎?

enter image description here

+0

你QUER由於第一個子查詢,所以寫成的y應該返回語法錯誤。所有的表都有'pid'上的索引嗎?儘管你可能會做更多的優化,但這可能會帶來足夠快的性能。 –

+0

@GordonLinoff,nop ...查詢的工作原理..但沒有索引pid ...在所有表中添加索引是我可以做的所有改善性能?我驚訝於自己..因爲sql不是我的區域... –

回答

1

下面是編寫查詢稍微更好的辦法:

SELECT p.*, (kills + reputation - deaths) as score 
FROM (SELECT (SELECT nick FROM nicks n WHERE n.pid = p.id ORDER BY id DESC LIMIT 1 
      ) as nick, 
      (SELECT COUNT(*) FROM kills k WHERE k.pid = p.id) as kills, 
      (SELECT COUNT(*) FROM deaths d WHERE d.pid = p.id) as deaths, 
      (SELECT COUNT(*) FROM headshots h WHERE h.pid = p.id) as headshots, 
      (SELECT COUNT(*) FROM votos v WHERE v.pid = p.id) as reputation 
     FROM players p 
     WHERE p.uuid = 'STEAM_x:x:xxxxxx' 
    ) p 
GROUP BY kills; 

注:我不明白什麼GROUP BY在做什麼。您只是按一列進行彙總,所以其餘列的值有,並且不確定值。也許你打算ORDER BY

我猜測在group by之前實現子查詢的開銷略小於其他子查詢。但是你的版本可能具有非常可比的性能。

對於任一版本,您希望達到以下指標:

  • players(uuid)
  • kills(pid)
  • deaths(pid)
  • headshots(pid)
  • votos(pid)
+0

非常感謝!你太棒了!!! –