简体   繁体   English

根据MYSQL中同一表中的另一列更新列中的值

[英]Update value in a column based on another column in the same table in MYSQL

I have a table that is having 3 columns 我有一个有3列的表

  1. vid - auto increment column vid - 自动增量列
  2. video_id - containing numbers video_id - 包含数字
  3. a_id - containing junk numbers a_id - 包含垃圾数字

The table looks like below. 该表如下所示。

Vid    Video_id    a_id
101     1            3
102     1            3
103     5            3
104     5            3
105     5            3
106     11           3
107     11           3
108     11           3
109     11           3
110     11           3         

I want to update a_id column values based on video_id values. 我想根据video_id值更新a_id列值。 Values in a_id should be updated as below.ex: If there are five 11 digit in video_id then the value in a_id should be updated 1 through 5. a_id中的值应更新如下.ex:如果video_id中有5个11位,则a_id中的值应更新1到5。

Vid    Video_id    a_id
101     1            1
102     1            2
103     5            1
104     5            2
105     5            3
106     11           1
107     11           2
108     11           3
109     11           4
110     11           5

You can use user defined variables to give rank for each video group and then join with your real table by your auto increment column and update a_id accordingly 您可以使用用户定义的变量为每个视频组提供排名,然后通过自动增量列与真实表联接并相应地更新a_id

update t
join (
    SELECT 
    Vid,
    @r:= CASE WHEN Video_id = @g THEN @r+1  ELSE @r:=1 END a_id 
    ,@g:=Video_id
    FROM t,(SELECT @r:=0,@g:=0) t1
    ORDER BY Video_id
) t1
on(t.Vid =t1.Vid)
set t.a_id = t1.a_id

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM