how to give same serial number for group of records in mysql

后端 未结 2 1037
名媛妹妹
名媛妹妹 2021-01-29 16:06

I am just new in mysql. I have records like below in carts table

 id   code
 1     100
 2     101
 3     102
 4     100
 5     100
 6     101

M

相关标签:
2条回答
  • 2021-01-29 16:58

    Your groups are defined by starting with code = 100. This is a little tricky. In MySQL 8+, you can use window functions to define the groups and then row_number() to assign the serial_number:

    select c.*, 
           row_number() over (partition by grp order by id) as serial_number
    from (select c.*,
                 sum( code = 100 ) over (order by id) as grp
          from carts c
         ) c;
    

    This is much more complicated in earlier versions of MySQL.

    You can identify the group using a subquery:

    select c.*,
           (select count(*)
            from carts c2
            where c2.id <= c.id and c2.code = 100
           ) as grp
    from carts c;
    

    You can then use variables to get the information you want:

    select c.*,
           (@rn := if(@g = grp, @rn + 1,
                      if(@g := grp, 1, 1)
                     )
           ) as serial_number
    from (select c.*,
                 (select count(*)
                  from carts c2
                  where c2.id <= c.id and c2.code = 100
                 ) as grp
          from carts c
          order by grp, id
         ) c cross join
         (select @g := -1, @rn := 0) params;
    
    0 讨论(0)
  • 2021-01-29 17:02

    According to your example you always have the same serial number for a code. So what do you gain?

    Here is the very simple query:

    select id, code, code - 99 as serial_number
    from mytable
    order by id;
    
    0 讨论(0)
提交回复
热议问题