Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to remove certain text from each field in a specific column?

Tags:

mysql

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?

like image 812
Josh Foskett Avatar asked Jan 28 '12 22:01

Josh Foskett


People also ask

How do I select only certain values in a column in SQL?

SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names. To retrieve all columns, use the wild card * (an asterisk).


2 Answers

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', '');
like image 196
Michael Berkowski Avatar answered Sep 19 '22 16:09

Michael Berkowski


This should work:

UPDATE MyTable
SET file_name = SUBSTRING(file_name,1, CHAR_LENGTH(file_name)-4)
like image 27
Bassam Mehanni Avatar answered Sep 18 '22 16:09

Bassam Mehanni