mysql update with regexp - mysql

I want to remove something from my table 1) 32) 121) 1000)... the format is number + )
I tried this code.
UPDATE articles SET
title= REPLACE(title,'\d)', '' )
WHERE title regexp "\d)*"
Nothing happened in phpmyadmin, how to write correct? Thanks.

You can't: Mysql doesn't support regex-based replace.
See this SO question for a work-around.

Finally, I use some php to solve this problem with a quickly method.
for ($i=1; $i<=9999; $i++){
$my_regex = $i.')';
mysql_query("UPDATE articles SET title = REPLACE(title,'".$i."', '' ) where title like '%".$i."%'");
}

I have unique requirement where I need to replace inactive owner username. Where username contians INACITVE followed by village id. So I have used concat() funacion inside replace() function to replace dynamically.
update Owner set username = replace(username, concat('_INACTIVE_',village_id) ,'')
where village_id = 3363010;

As an alternative, depending on the size of the table, you could do a workaround with substring function.

Related

Use DB::select + binding too select a row

I'm trying to get a row from the database but when using binding. I know that this doesn't work because the query automatically puts single quotes so it will be like this: select model, magazine, round('name', 2) etc. This doesn't work of course but how do I get rid of the single quotes?
$merkinformation = DB::select('select Model, Magazine, round(?, 2) as Rondetijd from rondetijden where Merk = ? order by ? limit 3;', [$track, $merk, $track]);
You can't use column nmaes like this.
You must concatinate the name of the column. But this is vulnerable to sql injection. So you must check if $track has a valid content
$merkinformation = DB::select('select Model, Magazine, round(`' . $track . '` , 2) as Rondetijd from rondetijden where Merk = ? order by ? limit 3;', [$merk, $track]);
there is ['] single quote and [`] punctuation mark. If start with single quote or double quote mysql will translate that as string where punctuation mark will be recognize as field name.
Are you sure that is a single quote ?

Rails update multiple record with hash

I need to update my data iteratively.
But the following way I achieved is the way too time-consuming.
Can I update multiple records with an id-value hash?
SUBST = ''.freeze
re = /<p>|<\/p>/m
(1..1000).each do |id|
choice = QuestionChoice.find id
choice.selections.gsub!(re, SUBST)
choice.save! if choice.changed?
end
Update:
Since I found out my code could be improved by using where
Like the following
QuestionChoice.where(id: (1..1000)).each do |choice|
choice.selections.gsub!(re, SUBST)
choice.save! if choice.changed?
end
But now I still need to call save! for every record which will cost much time.
You are hitting the db 1000 times sequentially to get each record separately, try to use single query to get all records you need to update:
SUBST = ''.freeze
re = /<p>|<\/p>/m
QuestionChoice.where('id <= 1000').map do |q|
q.selections.gsub!(re, SUBST)
q.save! if q.changed?
end
I used to face this problem and I solved it. Try to the following:
MySQL 8.0+:
QuestionChoice.where(id: 1..1000).update_all("selections = REGEXP_REPLACE(selections, '<p>|<\/p>', '')")
Others:
QuestionChoice.where(id: 1..1000).update_all("selections = REPLACE(selections, '</p>', '')")
or
QuestionChoice.where(id: 1..1000).update_all %{
selections =
CASE
WHEN selections RLIKE '<p>|<\/p>'
THEN REPLACE(selections,'<p>|<\/p>', '')
END
WHERE selections RLIKE '<p>|<\/p>'
}
IMPORTANT: Try to put a few backlashes (\) to your regex pattern in the clause if needed.

Remove last char if it's a specific character

I need to update values in a table by removing their last char if they ends with a +
Example:
John+Doe and John+Doe+ should both become John+Doe.
What's the best way to achieve this?
UPDATE table
SET field = SUBSTRING(field, 1, CHAR_LENGTH(field) - 1)
WHERE field LIKE '%+'
If you are trying to display the field instead of update the table, then you can use a CASE statement:
select
case
when right(yourfield,1) = '+' then left(yourfield,length(yourfield)-1)
else yourfield end
from yourtable
SQL Fiddle Demo
you didn't explain exactly the situation.
but if you search for names in a text. I'll remove all the non chars (anything not a-z and A-Z) including spaces and then compare.
if you want just the last char, try the SUBSTRING_INDEX function.
if you are passing to the DB as a string, you can do this with str_replace
<?php
$str = "John+Doe+";
$str = str_replace("+"," ",$str);
echo $str;
?>

Select nested AND OR. How?

Below I have an SQL query that servers as a login script for users who choose to either type in their username or email.
I've noticed that even though it seems it would check for either or as a login credential in doesn't.
username1 OR username1#email.com = Only really looking up by username
SELECT *
FROM tblaccount
WHERE acc_user='username1' OR acc_email='username1#email.com'
AND acc_password='letmein1' AND acc_confirmed='1' AND acc_active='1'
...if I alter it to...
username0 OR username1#email.com = It does not return a record.
Any thoughts?
Put some parentheses around those conditions with OR:
SELECT * FROM tblaccount
WHERE (acc_user = 'username1' OR acc_email = 'username1#email.com' )
AND acc_password = 'letmein1'
AND acc_confirmed = '1'
AND acc_active = '1';
Mahmoud's solution is correct. You will have to read the operator precedence in mysql.
http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html
As OR has low precedence than the AND, you will have to put the OR within the parenthesis as Mahmoud has provided.

Mysql replace query with regular expressions for forum quote tags

I'm looking for a way run a query which only replaces phrases within "[QUOTE=XXX]" tags.
For example:
[QUOTE=User Peter]Hello. This text should not be affected.[/QUOTE]
[QUOTE=Moderator John]Hello. This text should not be
affected.[/QUOTE]
I would like to remove the Phrase User and Moderator using a mysql query.
However, the following should also not be affected:
[QUOTE=Tom]Hello Moderator John.[/QUOTE]
This is my current query:
UPDATE post SET pagetext = REPLACE(REPLACE(pagetext, 'User', '') , 'Moderator', '') WHERE pagetext REGEXP '\\[QUOTE=*\\]';
I need some help with the regex part.
I hope you guys understand what I'm trying to do here.
Try see if this works;
UPDATE post SET pagetext = REPLACE(REPLACE(pagetext, 'User', '') , 'Moderator', '') WHERE pagetext LIKE '%[QUOTE=%';