19

I recently recoded one of my sites, and the database structure is a little bit different.

I'm trying to convert the following:

*----*----------------------------*
| id | file_name                  |
*----*----------------------------*    
| 1  | 1288044935741310953434.jpg |
*----*----------------------------*
| 2  | 1288044935741310352357.rar |
*----*----------------------------*

Into the following:

*----*----------------------------*
| id | file_name                  |
*----*----------------------------*    
| 1  | 1288044935741310953434     |
*----*----------------------------*
| 2  | 1288044935741310352357     |
*----*----------------------------*

I know that I could do a foreach loop with PHP, and explode the file extension off the end, and update each row that way, but that seems like way too many queries for the task.

Is there any SQL query that I could run that would allow me to remove the file exentision from each field in the file_name column?

4 Answers 4

54

You can use the REPLACE() function in native MySQL to do a simple string replacement.

UPDATE tbl SET file_name = REPLACE(file_name, '.jpg', '');
UPDATE tbl SET file_name = REPLACE(file_name, '.rar', '');
3
  • 2
    +1 OP should be careful if his data someday contains multiple extensions.
    – pilcrow
    Jan 28, 2012 at 23:04
  • 3
    some.rare.animal.jpg --> somee.animel carefull ;) Oct 9, 2015 at 14:59
  • 1
    @EdwinStoteler Indeed! A WHERE clause can prevent that perhaps with REGEXP to match the known pattern, or instead use substring operations to remove the extension in conjunction with a WHERE clause. Oct 9, 2015 at 15:04
3

This should work:

UPDATE MyTable
SET file_name = SUBSTRING(file_name,1, CHAR_LENGTH(file_name)-4)
1
  • 1
    right :) But if the OP runs this UPDATE more than once (say, as a nightly job to fix that day's records), it will chop away parts of already trimmed filenames.
    – pilcrow
    Jan 29, 2012 at 14:43
1

This will strip off the final extension, if any, from file_name each time it is run. It is agnostic with respect to extension (so you can have ".foo" some day) and won't harm extensionless records.

UPDATE tbl
   SET file_name =  TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(file_name, '.', -1) FROM file_name);
0

You can use SUBSTRING_INDEX function

SUBSTRING_INDEX(str,delim,count)

Where str is the string, delim is the delimiter (from which you want a substring to the left or right of), and count specifies which delimiter (in the event there are multiple occurrences of the delimiter in the string)

Example:

UPDATE table SET file_name = SUBSTRING_INDEX(file_name , '.' , 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.