简体   繁体   English

Mysql使用另一个表中的值更新Null列,并重复该顺序

[英]Mysql update a Null column with values from another table and repeat the order

I've a table named Series 我有一张桌子叫系列

 ID   NAME 
 1    generic  
 2    irregular  
 3    regular

Another table "Sections" which contains the column "series_id" and its currently NULL (for all rows). 另一个表“ Sections”包含列“ series_id”及其当前的NULL(对于所有行)。

 id title description series_id 1 Types produced Types of data produced NULL 2 Data standard Data and metadata standards NULL 3 Policies for access Policies for access and sharing NULL 4 Products of Research Products of Research NULL 5 Expected info Expected information NULL 6 Period of retention Period of data retention NULL 

I need to update the Sections table with id of Series table in a sequential order, and repeat the cycle till the end of Section rows. 我需要以序列表的ID顺序更新Sections表,并重复该循环直到Section行的末尾。 For example, 例如,

 id title description series_id 1 Types produced Types of data produced 1 2 Data standard Data and metadata standards 2 3 Policies for access Policies for access and sharing 3 4 Products of Research Products of Research 1 5 Expected info Expected information 2 6 Period of retention Period of data retention 3 

I came up with an initial query, but its setting the series_id as 1 for all rows. 我想出了一个初始查询,但是将所有行的series_id设置为1。 Also, I am unsure how to repeat the series_id for the remaining rows 另外,我不确定如何对其余行重复series_id

UPDATE sections t1
JOIN   series t2
ON     t1.series_id = t2.id
SET    t1.series_id = t2.id
WHERE  t1.series_id IS NULL;

Any guidance is appreciated. 任何指导表示赞赏。 Thanks in advance. 提前致谢。

May be this might help: 可能这可能会有所帮助:

SET @s =  MAX(id) From Series;
UPDATE sections t1
JOIN   series t2
ON     MOD(t1.id, @s) = MOD(t2.id, @s)
SET    t1.series_id = t2.id
WHERE  t1.series_id IS NULL;

You can't join both tables like that because there is no shared column. 您不能像这样连接两个表,因为没有共享列。 You can use a Unique Key with an extra column that has different values for all groups of 1,2,3 (eg A,B,C,D,E....) which will autoincrement series_id to 1,2,3. 您可以将唯一键与额外的列一起使用,该列对于所有1,2,3组(例如A,B,C,D,E ....)具有不同的值,这会将series_id自动递增为1,2,3。 This might be the fastest solution. 这可能是最快的解决方案。 The extra column can be dropped after series_id is updated. 在series_id更新后,可以删除多余的列。 Another way would be writing a procedure and using a loop. 另一种方法是编写过程并使用循环。

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

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