简体   繁体   中英

In MySql, how to create a sequential set of values based on a record id where a specific related_id is available

What I am attempting to do is populate a value of 1, 2, 3, 4 based on the sequence of the primary key id, from low to high, where a repetitive value is present. Also, only doing this update based on a class value of 'jt'.

Example:

ID   abstract_id   class   jump_no
101   123           st        null
102   123           st        null
103   123           jt        1
104   123           jt        2
105   205           jt        1
106   205           jt        2
107   205           jt        3
108   391           st        null

Currently my table has all null value for the jump_no column. I am trying to populate that sequence, per abstract_id grouping but only with a class value of 'jt'. So the 1, 2, 3, 4 "counter" restarts for every new abstract_id.

There are a couple ways to do this. One uses correlated subqueries. Another that I use more often uses user-defined variables :

update yourtable y 
join ( 
    select id, abstract_id, 
       case abstract_id 
                when @prev_abstract_id 
                then @jump_no := @jump_no + 1 
                else @jump_no := 1 AND @prev_abstract_id := abstract_id end jump_no
    from yourtable join (select @jump_no:=0, @prev_abstract_id:=0) t
    order by id, abstract_id) t on y.id = t.id
set y.jump_no = t.jump_no;

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