Add a field and insert an increment value

情到浓时终转凉″ 提交于 2019-12-01 11:22:01

问题


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    222     data3
8    333     data1
9    333     data2

and I'd like to insert a new field, called for example order, where for each ref, I'll set a crescent value. So the output should be :

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

can I do this with a simple query?

EDIT

The example above is just an example. This is my real table on the database :

CREATE TABLE `items` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `trackid` varchar(255) NOT NULL,
  `side` varchar(255) NOT NULL,
  `side_pos` char(2) NOT NULL default '#',
  `pos` int(11) NOT NULL,
  `hh` char(2) NOT NULL,
  `mm` char(2) NOT NULL,
  `ss` char(2) NOT NULL,
  `atl` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20229 DEFAULT CHARSET=utf8

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5695217/add-a-field-and-insert-an-increment-value

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