Mysql – trigger to update row number

countmariadbMySQLtrigger

I have a MariaDB table

id | key  | year | .... | position        
1  | key1 | 2004 | ... |  3   
2  | key1 | 2011 | ... |  2  
3  | key1 | 2017 | ... |  1    
4  | key2 | 1994 | ... |  2 
5  | key2 | 2004 | ... |  1    
6  | key3 | 2004 | ... |  1    
7  | key4 | 1980 | ... |  2 
8  | key4 | 2011 | ... |  1

Position is the row number within they Key field order by year descending

How can I create a trigger to autofill position when I insert, delete or update any row. thanks

Best Answer

If you are running MySQL8.0, you could drop the column position, and create a view like this:

CREATE VIEW view_amariadbtable AS 
SELECT 
  id, 
  `key`, 
  year, 
  RANK() OVER (PARTITION BY year ORDER BY year DESC,id DESC) as position 
FROM amariadbtable

BTW, you should NOT use reserved words as column name (key)