我可以使复杂COUNT的SQL语句更有效吗?

时间:2009-07-23 16:31:00

标签: sql mysql

我有一张所有棒球大联盟比赛的表格,其结构如下:

**Game**
id (int)
home_team_id (int)
away_team_id (int)
home_score (int)
away_score (int)
date (date)

我还有一张名为“ticket”的桌子,门票出售给不同的游戏:

**Ticket**
id (int)
game_id (int)
price (float)
time_sold (datetime)

我想运行一个MySQL查询,每个故障单列表与故障单销售时主页和客户团队的记录相匹配。我一直在用这个:

SELECT ticket.id, game.home_team_id AS Home, game.away_team_id AS Away,
(SELECT COUNT(game.id) FROM game WHERE game.date < DATE_SUB(ticket.time_sold, INTERVAL 1 DAY) AND (game.home_score > game.away_score AND game.home_team = Home OR game.away_score > game.home_score AND game.away_team = Away)) as home_team_wins
FROM ticket
JOIN game
ON game.id = ticket.game_id

问题是这个查询非常慢。我已经为游戏桌中的所有列编制了索引,并且除了售票表中的价格之外都有,但它仍然很慢。

有人可以建议我如何加快速度吗?

1 个答案:

答案 0 :(得分:1)

我认为SELECT子句中的标量选择子查询可能是罪魁祸首。我会尝试将其移至FROM子句。

试试这个,看它是否有帮助(我可能有语法错误,我今天没有可以测试的环境):

SELECT ticket.id
     , game.home_team_id AS Home
     , game.away_team_id AS Away
     , game_count
FROM (SELECT COUNT(game.id) as game_count FROM game WHERE game.date <  DATE_SUB(ticket.time_sold, INTERVAL 1 DAY AND (game.home_score > game.away_score AND game.home_team = Home OR game.away_score > game.home_score AND game.away_team = Away))) as home_team_wins
   ,ticket JOIN game ON game.id = ticket.game_id