MySQL细化查询

时间:2013-07-03 10:30:48

标签: mysql search

我正在使用以下查询给我一组最近20场比赛。我想找到他们在过去20场比赛中得分的目标,并通过(进球数,日期)订购结果:

SELECT * FROM (
     SELECT *, `against` AS `goalsF` , `for` AS `goalsA`
     FROM `matches` , `teams` , `outcomes`
     WHERE(
     `home_team_id`=7 AND `matches`.away_team_id = `teams`.team_id
     OR 
     `away_team_id`=7 AND `matches`.home_team_id = `teams`.team_id
     )
     AND `matches`.score_id = `outcomes`.outcome_id
     ORDER BY `date` DESC
     LIMIT 0 , 20
     ) res
ORDER BY `goalsF`

问题在于:

  • 如果我们正在寻找的球队是主队,我们需要计算“目标”。
  • 如果球队指挥客队,我们需要计算“目标对手”以找到他们的目标。

所以我需要做的就是:

if (`home_team_id`=7 AND `matches`.away_team_id = `teams`.team_id) 
 SELECT *, `for` AS `goalsF` , `against` AS `goalsA`


if (`away_team_id`=7 AND `matches`.home_team_id = `teams`.team_id) 
 SELECT *, `against` AS `goalsF` , `for` AS `goalsA`

但是,这必须在子集或结果上进行。我不确定这是否可行,但我不了解MYSQL。

非常感谢任何帮助。

艾伦。

1 个答案:

答案 0 :(得分:2)

首先,您确实需要学习ANSI标准join语法,将join条件放在on子句而不是from子句中。此外,别名可能使查询更具可读性。

以下是你想要的逻辑,虽然它不包括团队名称:

SELECT *
FROM (SELECT *,
             (case when m.home_team_id = 7 then o.against end) as `goalsF` ,
             (case when m.away_team_id = 7 then o.`for` end)  as `goalsA`
      FROM `matches` m join
           `outcomes` o
           on m.score_id = o.outcome_id
      WHERE m.home_team_id = 7 or m.away_team_id = 7
      ORDER BY `date` DESC
      LIMIT 0 , 20
     ) res
ORDER BY `goalsF`

要获得团队名称,您应该两次加入teams表,一次加入主队,一次加入客队。您可以在子查询中或之后执行此操作。明确提及您选择的列并在每个列引用中包含表别名也是一个好主意:

SELECT *
FROM (SELECT m.*, o.*,
             homet.team_name as hometeam_name, awayt.team_name as away_team_name,
             (case when m.home_team_id = 7 then o.against end) as `goalsF` ,
             (case when m.away_team_id = 7 then o.`for` end)  as `goalsA`
      FROM `matches` m join
           `outcomes` o
           on m.score_id = o.outcome_id join
           teams homet
           on homet.team_id = m.home_team_id join
           teams awayt
           on awayt.team_id = m.away_team_id
      WHERE m.home_team_id = 7 or m.away_team_id = 7
      ORDER BY `date` DESC
      LIMIT 0 , 20
     ) res 
ORDER BY `goalsF`

编辑:

要获得团队7的目标,您可以使用:

             (case when m.home_team_id = 7 then o.`for`
                   when m.away_team_id = 7 then o.against
              end) as goals

为了获得其他团队的目标:

             (case when m.home_team_id = 7 then o.against
                   when m.away_team_id = 7 then o.`for`
              end) as goals

编辑II:

要获得“其他”团队名称,逻辑是类似的。将select中的团队名称引用替换为:

             (case when m.home_team_id = 7 then awayt.team_name
                   when m.away_team_id = 7 then homet.team_name
              end) as goals