如何更新MYSQL表的clolum的具体部分

时间:2015-08-04 17:22:32

标签: mysql database

MYSQL表有2列。

id      image path

1255    /images/abc/1255.png
1256    /images/pqr/1256.png
1257    /images/rsrrrr/1255.png
1258    /images/fg&rrdr/1257.png
1259    /images/v/1255.png
1260    /images/r/1258.png

我想像这样更新图像路径:

id      image path

1255    /images/abc/1255.png
1256    /images/pqr/1256.png
1257    /images/rsrrrr/1257.png
1258    /images/fg&rrdr/1258.png
1259    /images/v/1259.png
1260    /images/r/1260.png

最后一个/后面的含义字符应该是“id”.png

任何人都可以帮助我。

3 个答案:

答案 0 :(得分:4)

这个应该适用于任何深度:

update tblName 
set image_path = concat(replace(image_path, SUBSTRING_INDEX(image_path, '/', -1), '') , id, '.png')

答案 1 :(得分:3)

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE Table1
    (`id` int, `image path` varchar(24))
;

INSERT INTO Table1
    (`id`, `image path`)
VALUES
    (1255, '/images/abc/1255.png'),
    (1256, '/images/pqr/1256.png'),
    (1257, '/images/rsrrrr/1255.png'),
    (1258, '/images/fg&rrdr/1257.png'),
    (1259, '/images/v/1255.png'),
    (1260, '/images/r/1258.png')
;

update table1 
set `image path` = replace(`image path`, 
                           SUBSTRING_INDEX(`image path`, '/', -1),
                           concat(id, '.png')
                          )

查询1

SELECT *
FROM Table1

<强> Results

|   id |               image path |
|------|--------------------------|
| 1255 |     /images/abc/1255.png |
| 1256 |     /images/pqr/1256.png |
| 1257 |  /images/rsrrrr/1257.png |
| 1258 | /images/fg&rrdr/1258.png |
| 1259 |       /images/v/1259.png |
| 1260 |       /images/r/1260.png |

答案 2 :(得分:1)

如果你的文件夹级别正好具有深度2,那么使用工作代码我测试过:

update tblName set image_path =
concat( 
SUBSTRING_INDEX((image_path),'/',1),
SUBSTRING_INDEX((image_path),'/',3),
'/',id, 
'.',SUBSTRING_INDEX(SUBSTRING_INDEX(image_path, '/', -1), '.', -1)  /*last path*/
)