I’m new to postgresql and need help with an update script where I can insert the corresponding ID between path2 and the filename if there is none.This will be done on multiple records.
table1 id name path 111 Test1 /path1/path2/file1.png 222 Test1 /path1/path2/222/file2.png 333 Test3 /path1/path2/file3.png 444 Test3 https:test/path1/path2/file4.png 555 Test4 /path1/path2/file5.png
After update only IDs 111 and 333 will be affected and the expected is /path1/path2/111/file1.png /path1/path2/333/file3.png
I am using this select to get the records that need updating.
select * from table1 where name in ('Test1','Test3') and path like '/path1/path2/%' and path not like '/path1/path2/%/%'
Advertisement
Answer
Please try this:
update table1 set path = replace(path, '/path2/', concat('/path2/', id::text, '/')) where path !~ concat('/path2/', id::text, '/'); UPDATE 4 select * from table1; id | name | path -----+-------+-------------------------------------- 222 | Test1 | /path1/path2/222/file2.png 111 | Test1 | /path1/path2/111/file1.png 333 | Test3 | /path1/path2/333/file3.png 444 | Test3 | https:test/path1/path2/444/file4.png 555 | Test4 | /path1/path2/555/file5.png (5 rows)