简体   繁体   中英

PHP MySQL Ranking will count order by number and sort by group

Let's say initially I has table like this without rank or already has rank if php code has running before

ID | STATUS | GRADE | RANK

1  | FAIL   |  99   |  
2  | FAIL   |  95   |  
3  | PASS   |  40   |  
4  | BAR    |  99   |  
5  | PASS   |  70   |  
6  | PASS   |  85   |  
7  | BAR    |  80   |  
8  | FAIL   |  60   |  
9  | BAR    |  50   |  

The ranking system should choose PASS > FAIL > BAR in order. But in that category, when start to enter new category the ranking system will count from previous.

Expected result:

ID | STATUS | GRADE | RANK

1  | FAIL   |  99   |  4
2  | FAIL   |  95   |  5
3  | PASS   |  40   |  3
4  | BAR    |  99   |  
5  | PASS   |  70   |  2
6  | PASS   |  85   |  1
7  | BAR    |  80   |  
8  | FAIL   |  60   |  6
9  | BAR    |  50   |  

Also if can show me some technique to edit the code so that in another day if i plan to upgrade the coding to

ID | STATUS | GRADE | RANK

1  | FAIL   |  99   |  4
2  | FAIL   |  95   |  5
3  | PASS   |  40   |  3
4  | BAR    |  99   |  7
5  | PASS   |  70   |  2
6  | PASS   |  85   |  1
7  | BAR    |  80   |  8
8  | FAIL   |  60   |  6
9  | BAR    |  50   |  9

I have try edit and learning some codes that I found here but I not familiar with session variable. This code will use in cron job/day

You can use user variables to set a rank, and using a sub query joined against the table you want to update you can update the rank in the table.

Something like this:-

UPDATE sometable
INNER JOIN
(
    SELECT id, 
        `status`, 
        grade,
        @rank:=@rank + 1 AS rank
    FROM
    (
        SELECT id, 
                `status`, 
                grade
        FROM sometable
        ORDER BY FIELD(`status`, 'PASS', 'FAIL', 'BAR'), Grade DESC
    ) sub0
    CROSS JOIN (SELECT @rank:=0) sub1
) sub2
ON sometable.id = sub2.id
SET sometable.rank = sub2.rank

Note that I have used the FIELD function to order by the status. In this case it is not strictly necessary (as you could order by status DESC) but given the names of the status would not normally be expect to be in a meaningful alphabetic order FIELD allows you to order in a specified order.

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