[英]Mysql update a Null column with values from another table and repeat the order
我有一張桌子叫系列
ID NAME
1 generic
2 irregular
3 regular
另一個表“ 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
我需要以序列表的ID順序更新Sections表,並重復該循環直到Section行的末尾。 例如,
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
我想出了一個初始查詢,但是將所有行的series_id設置為1。 另外,我不確定如何對其余行重復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;
任何指導表示贊賞。 提前致謝。
可能這可能會有所幫助:
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;
您不能像這樣連接兩個表,因為沒有共享列。 您可以將唯一鍵與額外的列一起使用,該列對於所有1,2,3組(例如A,B,C,D,E ....)具有不同的值,這會將series_id自動遞增為1,2,3。 這可能是最快的解決方案。 在series_id更新后,可以刪除多余的列。 另一種方法是編寫過程並使用循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.