简体   繁体   中英

How to make Students Position (ist, 2nd, 3rd, 4th) depending on their scores

            CREATE TABLE IF NOT EXISTS `users` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `names` varchar(30) NOT NULL,
            `matricno` varchar(30) NOT NULL,
            `class` varchar(30) NOT NULL,
            `scores` varchar(30) NOT NULL,
            `subject` varchar(30) NOT NULL,
        PRIMARY KEY (`id`)
        )   ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;




        $con = mysqli_connect("localhost", "root", "1024", "sch_one");
            if (!$con) {
                echo "Failed to connect to Database". mysqli_error();
        }



        INSERT INTO `users` (`id`, `names`, `matricno`, `class`, `scores`) VALUES
        (1, 'Henry Okon Etim', '15/HCSS/001', 'A', 800),
        (2, 'Henry Okon Etim', '15/HCSS/002', 'A',  804),
        (3, 'Etim Okon Etim', '15/HCSS/003', 'A',  820),
        (4, 'Lavalish Okon Etim', '15/HCSS/004',  'A', 730),
        (5, 'Pherema Okon Etim', '15/HCSS/005',  'A', 920),
        (6, 'Leman Okon Etim', '15/HCSS/006', 'A', 803),
        (7, 'Lema3 Okon Etim', '15/HCSS/007',  'A', 500);

I am on a project that gives students positions based on their final scores. My problem is how to output positions according to the scores in a as 1st, 2nd, 3rd, 4th, 5th and so on. Please explanations and codes are welcome. Thanks!

请尝试以下代码:

SELECT * FROM users ORDER BY scores DESC;

From what I'm understanding you want to pimary keys(1/2/3..) to reflect their position?

That's not what the id's are for, if you want to order them you can just add an order by in your get query.

$result = $mysqli->query("SELECT * FROM users ORDER BY scores desc");

If you really want an index/counter in your select, you could always take a look at ranking in mysql, end result would be something like this:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, users.* FROM users ORDER BY scores DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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