MySQL move part of a cell to another column - mysql

I have the following imported to TableA, Column 'Clothes' and Column 'Colours'
The problem is the import has put in the 'Clothes' column 'Jeans - Blue' and 'Jumper - Red' etc etc
Please could someone help me with a query to keep everything before the - in 'Clothes' and everything after the - into 'Colours' and removing the - altogether.

Two steps for this.
First, update the colors:
UPDATE yourTableA T
SET T.Colours = TRIM(SUBSTR(T.Clothes,INSTR(T.Clothes,'-') + 2));
Second, update the Clothes:
UPDATE yourTableA T
SET T.Clothes = TRIM(SUBSTR(T.Clothes,1,INSTR(T.clothes,'-')-1));
I've used SUBSTR as my string swiss army knife here, and INSTR to locate the position of the - in between. You can do without TRIM, but I usually use this in those cases to avoid unnecessary white spaces.
There surely are more direct ways to do it, but this'll work.

The SUBSTRING_INDEX function is convenient, and the TRIM function can remove leading and trailing spaces. For example:
SELECT TRIM(SUBSTRING_INDEX(a.Clothes,'-',1)) AS Clothes
, TRIM(SUBSTRING_INDEX(a.Clothes,'-',-1)) AS Colours
FROM TableA a
WHERE LENGTH(a.Clothes)-LENGTH(REPLACE(a.Clothes,'-','')) = 1
(NOTE: the query above is returning the substring before the first '-' character, and is returning the substring after the last '-' character. So any values with more than one dash would lose the portion between the first and last dashes, consider e.g. 'A - B - C - D', the query above returns the A and returns the D, and loses everything else.
To handle this anomaly, the WHERE clause checks that the string contains a single occurrence of the '-' character.
Once you have a query you are happy with, you can turn that into an UPDATE statement, BUT be VERY careful about the order you assign new values to columns. Unlike other relational databases, MySQL does not guarantee that a reference to an existing column within the statement will be the value of the column from the beginning of the statement... the only guarantee is that it will be the value that is currently assigned. So, the order that the columns is assigned is important!
UPDATE TableA a
SET Colours = TRIM(SUBSTRING_INDEX(a.Clothes,'-',-1))
, Clothes = TRIM(SUBSTRING_INDEX(a.Clothes,'-',1))
WHERE LENGTH(a.Clothes)-LENGTH(REPLACE(a.Clothes,'-','')) = 1
Note that if we were to assign the Clothes column before we assigned a value to the Colours column, the value we want assigned to Colours would be "lost".

You can do it in a single UPDATE as follows:
UPDATE TableA
SET `Colours` = SUBSTRING_INDEX(`Clothes`, ' - ', -1),
`Clothes` = SUBSTRING_INDEX(`Clothes`, ' - ', 1)
;
You can experiment with SQL Fiddle Demo I created from your data.
Here's the data I worked with:
CREATE TABLE TableA
(Clothes varchar(20), Colours varchar(20))
;
INSERT INTO TableA
(`Clothes`, `Colours`)
VALUES
('Jeans - Blue', NULL),
('Jumper - Red', NULL)
;
This the result of SELECT * FROM TableA; :
CLOTHES COLOURS
Jeans Blue
Jumper Red

Related

replace a character in mysql with a random character from a list

i would like to perform Mysql search & replace with random characters, taken from a list. I cannot use regex, since my version is way prior to 8.
instead of the below,
i would like to change for instance the letter u with one out of (a,e,i,f,k) randomly.
UPDATE products
SET
productDescription = REPLACE(productDescription,
'abuot',
'about');
Is there a mysql command for this task?
Actually my goal is to get in the lastnames column, new names that are not exactly like the real ones, so one could work on "anonymous" data.
I would like to replace all rows in a certain column. Say in table products, in column description, we have data like:
abcud
ieruie
kjuklkllu
uiervfd
With the replace function, we would not want to create something like: replace e with i,
but replace e with one of (a,e,i,f,k)
example desired output:
abced
ierfie
kjiklkllk
aiervfd
like i said, we plan to use this into last names, we plan to replace many characters with random ones from a list, in an effort to create anonymous data in the column that contains last names.
On a next step, i would like to do the same, in order to make anonymous telephone numbers.
example
726456273
827364878
347823472
replace 3 with one of 0-9,
output:
726456279
827664878
547821472
SELECT REPLACE('product abuot Description',
SUBSTRING('product abuot Description', CHARINDEX('abuot', 'product abuot Description') ,5) , 'about')
CREATE FUNCTION smart_replace ( argument TEXT,
search_for CHAR(1),
replace_with TEXT )
RETURNS TEXT
NO SQL
BEGIN
SET argument = REPLACE(argument, search_for, CHAR(0));
REPEAT
SET argument = CONCAT( SUBSTRING_INDEX(argument, CHAR(0), 1),
SUBSTRING(replace_with FROM CEIL(RAND() * LENGTH(replace_with)) FOR 1),
SUBSTRING(argument FROM 2 + LENGTH(SUBSTRING_INDEX(argument, CHAR(0), 1))));
UNTIL NOT LOCATE(CHAR(0), argument) END REPEAT;
RETURN argument;
END
replace e with one of (a,e,i,f,k)
SELECT smart_replace(table.column, 'e', 'aeifk')
replace 3 with one of 0-9
SELECT smart_replace(table.phone, 'e', '0123456789')

Left function leaving out characters

I have a database with over a 1,000 numbers in roughly the same format: aaa-111-2222
Some of the numbers have extra parts at the end: aaa-111-2222(bbbb)
I created a column and updated my table using the left function:
UPDATE table_1
SET col_2 = Left(col_1, 12)
I want to update the entire table so I didn't include a WHERE function.
The problem is when it updates, it is leaving off two characters.
Col_1: aaa-111-2222(bbbb)
when the function was ran it returned:
Col_2: aaa-111-22
Which is short characters. I thought that there might be some leading spaces I couldn't see, so on the orginal column I:
SELECT REPLACE(Col_1, " ","") FROM table_1
Then I reran my update and it was still returning short. I thought maybe I had extra returns and other white space, so I ran:
SELECT REPLACE(REPLACE(Col_1, CHAR(13), ''), CHAR(10), '') FROM table_1
Then I deleted Col_2 and remade it again. The structure was VARCHAR, with a Length of 15 (Which is 3 more than I should have)
After I ran the UPDATE again, it is still short 2 characters.
Any ideas on what I else I can do to fix?
May be there are leading spaces in col_1. The REPLACE did not update col_1 as it only applies the resulting dataset of the SELECT. Try use TRIM to eliminate the leading and trailing spaces to see if it makes any difference:
UPDATE table_1
SET col_2 = Left(TRIM(col_1), 12) ;
Also try this:
UPDATE table_1
SET col_2 = LEFT(TRIM(REPLACE(REPLACE(col_1,'\r',''),'\n','')), 12);
I ended up noticing that my table was 3 times bigger than it should have been. I emptied the table, reloaded it with backup data I had, then did the REPLACE and after that it worked just fine.
Thank you guys for the tips.

I want to insert a value multiple time in a same field without disturbing the previous data

eg : field name = User_id
Value=abc later i want to insert xyz without disturbing abc Value= abc,xyz i want to insert efg without disturbing abc then Value= abc,xyz,efg and so on
i want to seperating each value by using ","(comma). can any one help me out
In MySQL you could often refer to the value of a column just by using the column name. And to concatenate strings with a separator there's a nifty function called concat_ws (concat with separator).
In your case the code would look something like
UPDATE YourTable
SET Value = CONCAT_WS(',', Value, 'cde')
WHERE User_id = 123;
Good Luck!
MySQL CONCAT_WS() function is used to join two or more strings with separator. The separator specified in the first argument is added between two strings. The separator itself can be a string. If the separator is NULL the result is NULL.
Click hear for more information

update specific column of mysql table

I have a quite big table in mysql and I need to change all the records related to this column.
records are like this :
/name/nm0000209/?ref_=ttfc_fc_cl_t1,
/name/nm0000151/?ref_=ttfc_fc_cl_t2,
...,
/name/nm0104594/?ref_=ttfc_fc_cl_t10
what I want is to keep only the string in the middle which is nm0000209, nm0000151,.... I know how to delete specific characters from the right or left of the words by REPLACE or Trim , .., but my problem is that in this case the number of characters in the third part of string are not equal (as you see when it reaches to 10, I have to delete 21 characters from the end instead of 20 characters and since this table contains lots of records I dont know how to do it.
I reaaly appreciate if someone could helop me,
thanks
I want is to keep only the string in the middle which is nm0000209, nm0000151...
You can use 'SUBSTRING_INDEX' on the column to crop part of the column value.
Following example assumes that the said column will have 'name/' as starting pattern.
Example:
update table_name
set column_name = substring_index(
substring_index( column_name, 'name/', -1 )
, '/', 1 );
The same can be used for updating with the same value.
Demo # MySQL Fiddle
One approach would be to use MYSQL's SUBSTRING_INDEX function. It would let you get whatever's after the last slash. Or after the second to last.
For your particular case
select
SUBSTRING_INDEX(SUBSTRING_INDEX(thefield,'/',-2 ),'/', 1)
from supertext
would yield the desired result
EDIT: for update purposes
UPDATE thetable
SET thefield=SUBSTRING_INDEX(SUBSTRING_INDEX(thefield,'/',-2 ),'/', 1)

MySQL - is it possible to update only part of value from current column?

Here is an example table on which I would like to execute a query:
Structure of table_1
number | photos (CHAR,4)
1234 | 1210
I would like to update value from column photos, but without changing the whole value. I would like change, for example, only third character to "2" without knowing the whole value. How can I do that?
I know I could do that in this way described below, but the problem is the value may be variable and it is a column type CHAR, not INT.
UPDATE table_1 SET photos = (photos + 10) where number='1234'
Yes with mid, left and right functions because photos is a type char:
UPDATE table_1 SET photos =
concat(
left( photos, 2),
'1',
right( photos, 1)
)
where number='1234'
Use concat(), left() and substring()
The example above would look like this:
update table_1
set photos = concat(left(photos, 2), "2", substring(photos, 4))
where number = '1234'
The advantage to this over left/right, is this will work for variable lengths of "photos".
Looking at it more generally, if you want to set the xth position to "2":
update table_1
set photos = concat(left(photos, x-1), "2", substring(photos, x+1))
where number = '1234'
(NOTE: I don't have MySQL running right now so I can't test the above. There are certain to be off-by-one errors which should be easy for your to correct)
If the column contains only numbers then the example you gave would work. The value will be converted to an integer, added to, and then converted back.
You might want to explain your reasoning for wanting to do this though. It seems a bit strange.