具有join和group by的同一个表上的SQL查询

时间:2013-07-13 10:09:14

标签: mysql sql join group-by

我对此查询有疑问:

SELECT source.cod,source.nome,source.ruolo,SUM(source.giocato),ROUND(SUM(source.fvoto)/SUM(source.giocato),2) as media,ROUND(SUM(source.voto)/SUM(source.giocato),2),SUM(source.gs),SUM(source.ass),SUM(source.amm),SUM(source.esp),SUM(source.rigsub),SUM(source.rigpar),source.stagione,parent.stagione,parent.cod,parent.squadra,parent.valore,parent.esiste,parent.gg
FROM db_dati source
WHERE source.ruolo=".$q." AND source.stagione=".$stagione."
GROUP BY source.cod,source.politico,source.stagione
HAVING source.politico=0
JOIN db_dati parent
ON source.stagione=parent.stagione AND source.cod=parent.cod
ORDER BY media DESC

但它总是回应我:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'JOIN db_dati parent ON source.stagione = parent.stagione AND   第1行的source.cod = parent.cod'

2 个答案:

答案 0 :(得分:2)

您需要在WHERE子句之前连接表:

SELECT source.cod,source.nome,source.ruolo,SUM(source.giocato),ROUND(SUM(source.fvoto)/SUM(source.giocato),2) as media,ROUND(SUM(source.voto)/SUM(source.giocato),2),SUM(source.gs),SUM(source.ass),SUM(source.amm),SUM(source.esp),SUM(source.rigsub),SUM(source.rigpar),source.stagione,parent.stagione,parent.cod,parent.squadra,parent.valore,parent.esiste,parent.gg
FROM db_dati source
JOIN db_dati parent
ON source.stagione=parent.stagione AND source.cod=parent.cod
WHERE source.ruolo=".$q." AND source.stagione=".$stagione."
GROUP BY source.cod,source.politico,source.stagione
HAVING source.politico=0
ORDER BY media DESC

答案 1 :(得分:0)

那里有一些多余的东西......

 SELECT source.cod
      , source.nome
      , source.ruolo
      , SUM(source.giocato)
      , ROUND(SUM(source.fvoto)/SUM(source.giocato),2) media
      , ROUND(SUM(source.voto)/SUM(source.giocato),2)
      , SUM(source.gs)
      , SUM(source.ass)
      , SUM(source.amm)
      , SUM(source.esp)
      , SUM(source.rigsub)
      , SUM(source.rigpar)
      , source.stagione
      , parent.stagione
      , parent.cod
      , parent.squadra
      , parent.valore
      , parent.esiste
      , parent.gg
   FROM db_dati source
   JOIN db_dati parent
     ON parent.stagione = source.stagione 
    AND parent.cod = source.cod
  WHERE source.ruolo = ".$q." 
    AND source.stagione=".$stagione."
    AND source.politico=0
  GROUP 
     BY source.cod
  ORDER BY media DESC