0

我正在使用以下查询为我提供一组最近 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 的了解。

任何帮助将不胜感激。

艾伦。

4

1 回答 1

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

编辑二:

要获得“其他”团队名称,逻辑类似。将其中的团队名称引用替换为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
于 2013-07-03T10:42:55.430 回答