Reputation: 45
I'm new to SQL and I need some help with this task:
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.
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 =)
Upvotes: 0
Views: 83
Reputation: 48169
Since the "p.alias" is the same as "f.hero", why join to get the count. Also, since you are returning a limit of 1, why not include the alias with the count so you already have that. 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.
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
Upvotes: 1