简体   繁体   English

使用MAX()的简单SQL查询

[英]Simple SQL query with MAX()

I'm new to SQL and I need some help with this task: 我是SQL的新手,我需要一些有关此任务的帮助:

Database schema: 数据库模式:

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)

Now I shall declare a SQL query which gives the first and last names of those powered person(s) that fought the most enemies in just one comic. 现在,我将声明一个SQL查询,该查询给出在一个漫画中与最多敌人战斗的那些有能力的人的名字和姓氏。

My solution is this: 我的解决方案是这样的:

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)

I want to know if my solution is correct and in case it is, whether there is a much smarter and shorter way to solve this. 我想知道我的解决方案是否正确,万一是正确的,是否有更聪明,更短的方法来解决这个问题。

Thanks in advance =) 在此先感谢=)

Since the "p.alias" is the same as "f.hero", why join to get the count. 由于“ p.alias”与“ f.hero”相同,因此为什么要加入以获得计数。 Also, since you are returning a limit of 1, why not include the alias with the count so you already have that. 另外,由于返回的限制为1,为什么不将别名包含在计数中,所以您已经拥有了。 Do it all in one AND be done. 一次完成所有操作并完成。 Also, as a newbie to SQL, get in the habit of ALWAYS using "table.column" or "tableAlias.column" to prevent ambiguities in where columns come from more complex queries in the future. 另外,作为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM