Neliswa Astute Neliswa Astute - 8 days ago 5
MySQL Question

Why returns NULL after running select query the second time

I have select query that selects student scores and ranks them from the highest to the lowest, this mysql query works the first time, but when I run it the second time on phpmyadmin, it returns NULL where it is supposed to show the rank of the student, below is the mysql query;

SELECT @rownum := @rownum + 1 AS rank, student_name, avga FROM `averaga` WHERE class="Form 1A" ORDER BY avga DESC


here is a part snapshot of the results from query results
part snapshot of the results from query results

Answer

You need to initialize the variable. I usually do this in query itself:

SELECT (@rownum := @rownum + 1) AS rank, student_name, avga
FROM `averaga` a CROSS JOIN
     (SELECT @rownum := 0) params
WHERE class = 'Form 1A'
ORDER BY avga DESC;
Comments