MAX()的简单SQL查询

时间:2013-12-19 00:57:05

标签: sql

我是SQL的新手,我需要一些帮助来完成这项任务:

数据库架构:

Comic(no primary key NOT NULL, title, pages, publisher)
PoweredPerson(alias primary key NOT NULL, firstname NOT NULL, lastname, evilness_level)
SuperHero(alias primary key→PoweredPerson NOT NULL,cape)
SuperVillain(alias primary key→PoweredPerson NOT NULL)
FightIn(comic primary key→ Comic NOT NULL,hero primary key→ SuperHero NOT NULL,villain primary key→ SuperVillain NOT NULL)

现在我将声明一个SQL查询,该查询给出了那些在一个漫画中与最多敌人作战的有权人的名字和姓氏。

我的解决方案是:

SELECT firstname,lastname
FROM fightIn f 
JOIN poweredperson p
ON f.hero = p.alias OR f.villain= p.alias
GROUP BY comic,alias
HAVING COUNT(alias)=(SELECT COUNT(alias)
                     FROM fightIn f 
                     JOIN poweredperson p
                     ON f.hero = p.alias OR f.villain = p.alias
                     GROUP BY comic,alias
                     ORDER BY COUNT(hero) DESC
                     LIMIT 1)

我想知道我的解决方案是否正确,如果是的话,是否有更聪明,更短的方法来解决这个问题。

提前致谢=)

1 个答案:

答案 0 :(得分:1)

由于“p.alias”与“f.hero”相同,为什么要加入计数。此外,由于您返回的限制为1,为什么不包含带计数的别名,所以您已经拥有了。做到这一切并完成。此外,作为SQL的新手,养成使用“table.column”或“tableAlias.column”的习惯,以防止将来更复杂的查询列中出现歧义。

SELECT
      p.firstname,
      p.lastname,
      MostFights.hero,
      MostFights.Comic,
      MostFights.FightsInComic
   from
      ( SELECT
              f.Comic,
              f.hero,
              COUNT(*) as FightsInComic
           from 
              fightIn f
                 left join SuperVillain sv
                    on f.hero = sv.alias
           where
              sv.alias IS NULL
           group by
              f.Comic,
              f.hero
           order by
              COUNT(*) desc
           limit 1 ) MostFights
      JOIN PoweredPerson p
         ON MostFights.hero = p.alias