Add a field and insert an increment value

前端 未结 2 647
执念已碎
执念已碎 2021-01-15 22:32

I have this table :

id   ref     data
1    111     data1
2    111     data2
3    111     data3
4    111     data4
5    222     data1
6    222     data2
7             


        
相关标签:
2条回答
  • 2021-01-15 23:01

    MySQL doesn't support analytics (IE: ROW_NUMBER), which are what you'd use for the output you're after. Use:

    SELECT x.id, x.ref, x.data, x.rank AS `order`
      FROM (SELECT t.id, t.ref, t.data
                   CASE 
                     WHEN @ref = t.ref THEN @rownum := @rownum + 1
                     ELSE @rownum := 1
                   END AS rank,
                   @ref := t.ref
              FROM YOUR_TABLE t
              JOIN (SELECT @rownum := NULL, @ref := -1) r
          ORDER BY t.id, t.ref, t.data) x
    

    Usually, this would require separate statements to declare the @rownum and @ref variables but MySQL lets you get away with it if they are defined like you see in the example.

    The CASE statement resets the @rownum value to one if the ref values don't match. Otherwise, @rownum increments by one. The column the incrementing @rownum value is associated with is determined by the ORDER BY clause.

    0 讨论(0)
  • 2021-01-15 23:02

    I believe if you create a primary key that looks like (ref, order) where order is an auto_increment, you can have have the database create this for you automatically.

    http://mysqldump.azundris.com/archives/5-AUTO_INCREMENT-Trivia.html

    0 讨论(0)
提交回复
热议问题