开发者

Add a field and insert an increment value

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 :

开发者_JAVA百科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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜