You are here
Ranking in MySQL results
Fri, 2008-01-18 12:06 — Shinguz
A friend of me asked me long time ago: "How can I have a ranking on a result with MySQL?". Now I found some time to write it down:
Lets do first some preparation for the example:
CREATE TABLE sales ( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , fruit VARCHAR(32) , amount DECIMAL ); INSERT INTO sales VALUES (NULL, 'apple', 12.75), (NULL, 'orange', 1.89), (NULL, 'pear', 19.23) , (NULL, 'banana', 4.25), (NULL, 'cherry', 123.75), (NULL, 'plum', 23.15) ;
Now lets query:
SELECT fruit, amount FROM sales ORDER BY amount DESC ; +--------+--------+ | fruit | amount | +--------+--------+ | cherry | 124 | | plum | 23 | | pear | 19 | | apple | 13 | | banana | 4 | | orange | 2 | +--------+--------+
Hmmmm...., this not yet what we want!
And now with ranking:
SET @rank=0; SELECT @rank:=@rank+1 AS rank, fruit, amount FROM sales ORDER BY amount DESC ; +------+--------+--------+ | rank | fruit | amount | +------+--------+--------+ | 1 | cherry | 124 | | 2 | plum | 23 | | 3 | pear | 19 | | 4 | apple | 13 | | 5 | banana | 4 | | 6 | orange | 2 | +------+--------+--------+
Much better!
An other possibility would be, to do the whole ranking in the application (on the application server).
If you liked this article and if you have some more MySQL related questions consider our Consulting Services!
- Shinguz's blog
- Log in or register to post comments