Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mysql - Want Row Number on Group of column in MY SQL?

I have one table in MYSQL It has data like

Id Name 
1  test
1  test
1  test123
2  test222
3  test333

I want the data like

Id Name     RowNum
1  test       1
1  test       2
1  test123    1
2  test222    1
3  test333    1

Means i want assign row number on group of Id and Name ?

what should the script for same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This table definition will achieve what you want.

CREATE TABLE  `test` (
  `Id` int(10) unsigned NOT NULL,
  `Name` varchar(45) NOT NULL,
  `RowNum` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Id`,`Name`,`RowNum`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Populate table with data

INSERT INTO test VALUES
(1,"test",null),
(1,"test",null),
(1,"test123",null),
(2,"test222",null),
(3,"test333",null);

Select data from table

SELECT * FROM test;

Result

1, 'test', 1
1, 'test', 2
1, 'test123', 1
2, 'test222', 1
3, 'test333', 1

For doing it in a query here is a rather crude way of doing it.

select g.id,g.name,g.rownum 
from (
    select t.id,t.name,
        @running:=if(@previous=concat(t.id,t.name),@running,0) + 1 as rownum,
        @previous:=concat(t.id,t.name) 
    from test t
    order by concat(t.id,t.name) 
) g;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...