简体   繁体   中英

SQL : get substring from one column and inserting it into other column

First column contains image files names:

abcd.jpg
abcdef.png
...
abcdjs.xyz

I want to make another column which contains extensions of these image files:

jpg
png
... 
xyz

But some image files are named like ab.gefs.jpg .

I am not able to take the string after the last (.) dot.

You could reverse the file name, so that extension comes first and reversed, then locate the first dot, then cut everything before the dot -- that would be the reversed extension --, then reverse again:

UPDATE some_table t1, some_table t2
SET t1.some_column = REVERSE(SUBSTRING(REVERSE(t2.filename) FROM 1 FOR LOCATE('.', REVERSE(t2.filename))))
WHERE t1.primary_key = t2.primary_key;

MySQL's SUBSTRING_INDEX() function is pretty much tailor made for what you're trying to do:

> select substring_index( 'foo.png', '.', -1 );
+---------------------------------------+
| substring_index( 'foo.png', '.', -1 ) |
+---------------------------------------+
| png                                   |
+---------------------------------------+
1 row in set (0.01 sec)

> select substring_index( 'foo.bar.jpg', '.', -1 );
+-------------------------------------------+
| substring_index( 'foo.bar.jpg', '.', -1 ) |
+-------------------------------------------+
| jpg                                       |
+-------------------------------------------+
1 row in set (0.00 sec)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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