Add a field and insert an increment value

北战南征 提交于 2019-12-01 13:00:49

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!