Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为mysql数据库中的列指定递增的整数值_Mysql_Sql_Sql Update - Fatal编程技术网

为mysql数据库中的列指定递增的整数值

为mysql数据库中的列指定递增的整数值,mysql,sql,sql-update,Mysql,Sql,Sql Update,我们有一个应用程序,其中我们有一些学习路径,每个学习路径都与一些课程相关联。学习路径和课程之间的关联存储在mysql表中。现在,我们还希望在“学习路径到课程映射”中存储课程位置,因此我在表中添加了另一列“位置”,并希望通过查询来回填其中的现有数据,以便以任意随机方式为每个课程分配一个从1开始的数字,每个学习路径的数字应从1开始。比如说, LP1|C1 LP1|C1|1 LP1|C2 ==> LP1|C2|2 LP1|C3 LP1|C3|3 LP2|C

我们有一个应用程序,其中我们有一些学习路径,每个学习路径都与一些课程相关联。学习路径和课程之间的关联存储在mysql表中。现在,我们还希望在“学习路径到课程映射”中存储课程位置,因此我在表中添加了另一列“位置”,并希望通过查询来回填其中的现有数据,以便以任意随机方式为每个课程分配一个从1开始的数字,每个学习路径的数字应从1开始。比如说,

LP1|C1         LP1|C1|1
LP1|C2   ==>   LP1|C2|2
LP1|C3         LP1|C3|3
LP2|C1         LP2|C1|1
LP2|C5         LP2|C5|2

如果您运行的是MysQL 8.0,您只需使用row_number即可:

select 
    learning_path, 
    course, 
    row_number() over(partition by learning_path order by course) position
from mytable
如果需要更新查询:

在早期版本中,一个选项是:

update mytable t
inner join (
    select 
        learning_path, 
        course, 
        (select 1 + count(*) from mytable t1 where t1.learning_path = t.learning_path and t1.course < t.course) position
    from mytable t
) t1 on t1.learning_path = t.learning_path and t1.course = t.course
set t.position = t1.position

这不合理地假设数字不超过9我们使用的是5.7版。12@Strawberry:是的,否则OP需要像“Cnn”这样的课程。@Manishrichariya:我在回答中添加了对早期版本的查询。是的,或者只是“n”。
update mytable t
inner join (
    select 
        learning_path, 
        course, 
        (select 1 + count(*) from mytable t1 where t1.learning_path = t.learning_path and t1.course < t.course) position
    from mytable t
) t1 on t1.learning_path = t.learning_path and t1.course = t.course
set t.position = t1.position