我在MYSQL中有一个表它有数据
Id Name 1 test 1 test 1 test123 2 test222 3 test333
我想要像这样的数据
Id Name RowNum 1 test 1 1 test 2 1 test123 1 2 test222 1 3 test333 1
意味着我想在Id和Name组上分配行号?
脚本应该怎么样?
这个表定义将实现你想要的.
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;
Run Code Online (Sandbox Code Playgroud)
用数据填充表
INSERT INTO test VALUES
(1,"test",null),
(1,"test",null),
(1,"test123",null),
(2,"test222",null),
(3,"test333",null);
Run Code Online (Sandbox Code Playgroud)
从表中选择数据
SELECT * FROM test;
Run Code Online (Sandbox Code Playgroud)
结果
1, 'test', 1
1, 'test', 2
1, 'test123', 1
2, 'test222', 1
3, 'test333', 1
Run Code Online (Sandbox Code Playgroud)
对于在查询中执行此操作,这是一种相当粗略的方法.
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;
Run Code Online (Sandbox Code Playgroud)
这是另一种更简单的查询方式(至少对我而言):
SELECT
a.Id, a.Name,
(SELECT COUNT(*) FROM test
WHERE Id = a.Id AND `Name` = a.Name AND row_id < a.row_id) AS RowNum
FROM test AS a
ORDER BY a.row_id;
Run Code Online (Sandbox Code Playgroud)
这假设存在全局row_id(例如表中的自动增量主键).