I wrote a SQL query that outputs a list of clan ids and their positions.
SET @n := 0;
SELECT id, @n := @n + 1 AS position
FROM (
SELECT clans.id, SUM(clans_members.xp) AS xps
FROM clans
INNER JOIN clans_members ON clans_members.clans_id = clans.id
GROUP BY clans.id
ORDER BY xps DESC
) AS s;
Result:
But if I add WHERE id = 6 (as seen in the previous screenshot, the position of the clan with id 6 is 3), it outputs this result:
Even if I specify any other id, it will still output position 1. What to do and how to fix it?
2
Answers
You should use
HAVING
clause instead ofWHERE
clause in your case.Since you’re using MySQL v8, you can do something like this:
Use ROW_NUMBER() OVER () to generate row number on your original query, wrap that in a common table expression(cte) then filter the
id=6
.Demo fiddle