2017-04-08 89 views
0

這是一個查詢,計算玩遊戲,贏得每個玩家的吸引和損失,以及他們的積分總數。好像我重複了很多相同的查詢元素。我希望一雙新鮮的眼睛可能會讓我更有效率。簡化查詢:避免在mysql中重複計算

GAMES -> 
GameID,  GameDate,  Winner 
1   xxxx-xx-xx  A 
2   xxxx-xx-xx  D 
3   xxxx-xx-xx  B 

SELECTIONS -> 
GameID,  PlayerID,  Team 
1   1    A 
1   2    B 
2   1    A 
2   2    B 
3   1    A 
3   2    B 

PLAYERS -> 
PlayerID, Name 
1   John 
2   Mike 


QUERY -> 

SELECT 
    Selections.PlayerID, 
    Players.Name, 
    COUNT(Games.Winner=Selections.Team)+COUNT(Games.Winner='D')+COUNT(Games.Winner!='D' OR Games.Winner!=Selections.Team) 
     AS GamesPlayed, 
    COUNT(Games.Winner=Selections.Team) 
     AS GamesWon, 
    COUNT(Games.Winner='D') 
     AS GamesDrawn, 
    COUNT(Games.Winner!=Selections.Team OR Games.Winner!='D') 
     AS GamesLost, 
    (COUNT(Games.Winner=Selections.Team)*3)+(COUNT(Games.Winner='D')) 
     AS Points 

FROM 
    Games,Players,Selections 
WHERE 
    Games.Winner=Selections.Team 
AND 
    Players.PlayerID=Selections.PlayerID 
AND 
    Games.GameID=Selections.GameID 
GROUP BY 
    Selections.PlayerID; 

EXPLAIN

+----+-------------+------------+------------+--------+---------------+---------+---------+-------------------------+------+----------+----------------------------------------------------+ 
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref      | rows | filtered | Extra            | 
+----+-------------+------------+------------+--------+---------------+---------+---------+-------------------------+------+----------+----------------------------------------------------+ 
| 1 | SIMPLE  | Players | NULL  | ALL | PRIMARY  | NULL | NULL | NULL     | 2 | 100.00 | Using temporary; Using filesort     | 
| 1 | SIMPLE  | Selections | NULL  | ALL | NULL   | NULL | NULL | NULL     | 6 | 16.67 | Using where; Using join buffer (Block Nested Loop) | 
| 1 | SIMPLE  | Games  | NULL  | eq_ref | PRIMARY  | PRIMARY | 4  | btest.Selections.GameID | 1 | 33.33 | Using where          | 
+----+-------------+------------+------------+--------+---------------+---------+---------+-------------------------+------+----------+----------------------------------------------------+ 

回答

0

@learning豎起,並迅速刪除一個版本,它奏效了以下修改查詢。我從他的查詢編輯的唯一包含/* */之間

SELECT 
Selections.PlayerID, 
Players.Name, 
@win:=COUNT(Games.Winner=Selections.Team) 
    AS GamesWon, 
@draw:=COUNT(Games.Winner='D') 
    AS GamesDrawn, 
@lost:=COUNT(Games.Winner!=Selections.Team OR Games.Winner!='D') 
    AS GamesLost, 
(@win*3)[email protected] 
    AS Points, 
@[email protected][email protected] 
    AS GamesPlayed 
FROM 
Games,Players,Selections /*, (select @lost:=0,@win:=0,@draw:=0) c */ 
WHERE Games.Winner=Selections.Team 
AND Players.PlayerID=Selections.PlayerID 
AND Games.GameID=Selections.GameID 
GROUP BY Selections.PlayerID; 

被註釋掉位明顯重置變量爲0,但它並沒有使用它。

有什麼問題在生產現場評論這條線?