MySQL substring between two strings - mysql

I need a hand to solve a problem with my column field.
I need to extract the string in between these two different "patterns" of strings for example:
[...string] contract= 1234567890123350566076070666 issued= [string
...]
I want to extract the string in between 'contract=' and 'issued='
At the present moment I'm using
SELECT substring(substring_index(licence_key,'contract=',-1),1,40) FROM table
The problem is that this string in between doesn't have always 40 characters so it's not fixed length and so the data that comes before and after that. It's a volatile data.
Do you known how I can handle that?

Just use substring_index() twice:
SELECT substring_index(substring_index(licence_key, 'contract=', -1),
'issued=', 1)
FROM table;

If this string does not match then give the total result.
If you want to replace then you can use like this.
UPDATE questions set question= REPLACE(question, '<xml></xml>', '') WHERE question like '%<xml>%';
UPDATE questions set question= REPLACE(question, substring_index(substring_index(question, '<xml>', -1), '</xml>', 1), '') WHERE question like '%<xml>%';

Related

SQL replace all specified keys

I have one column(varchar) containing only json string within one table. I want replace all keys with "" on that column. How can I do that using sql? My database is MySQL.
For example:
|--------------------------------------------------------------------|
| t_column |
|--------------------------------------------------------------------|
| {"name":"mike","email":"xxx#example.com","isManage":false,"age":22}|
|--------------------------------------------------------------------|
SELECT replace(t_column, regexp, "") FROM t_table
I expect:
mikexxx#example.comfalse22
How to write that regexp?
Start from
select t_column->'$.*' from test
This will return a JSON array of attribute values:
[22, "mike", "xxx#example.com", false]
This might be already all you need, and you can try something like
select *
from test
where t_column->'$.*' like '%mike%';
Unfortunately there seems to be no native way to join array values to a single string like JSON_ARRAY_CONCAT(). In MySQL 8.0 you can try REGEXP_REPLACE() and strip all JSON characters:
select regexp_replace(t_column->'$.*', '[" ,\\[\\]]', '') from test
which will return '22mikexxx#example.comfalse'.
If the values can contain one of those characters, they will also be removed.
Note: That isn't very reliable. But it's all I can do in a "simple" way.
See demo on db-fiddle.
I could be making it too simplistic, but this is just a mockup based on your comment. I can formalize it into a query if it fits your requirement.
Let's say you get your JSON string to this format where you replace all the double quotes and curly brackets and then add a comma at the end. After playing with replace and concat_ws, you are now left with:
name:mike,email:xxx#example.com,isManage:false,age:22,
With this format, every value is now preceded by a semicolon and followed by a comma, which is not true for the key. Let's say you now want to see if this JSON string has the value "mike" in it. This, you could achieve using
select * from your_table where json_col like '%:mike,%';
If you really want to solve the problem with your approach then the question becomes
What is the regex that selects all the undesired text from the string {"name":"mike","email":"xxx#example.com","isManage":false,"age":22} ?
Then the answer would be: {\"name\":\"|\"email\":\"|\",\"isManage\":|,\"age\":|}
But as others let you notice I would actually approach the problem parsing JSONs. Look up for functions json_value and json_query
Hope I helped
PS: Keep close attention on how I structured the bolded sentence. Any difference changes the problem.
EDIT:
If you want a more generic expression, something like select all the text that is not a value on a json-formatted string, you can use this one:
{|",|"\w+\":|"|,|}

Finding exact value in mysql

I'm trying to solve problem how to find exact value from string.
The problem is then searching in Column StringB for the value 1, it finds all rows containing 1. The idea is that if I look for value 1 in StringB it should only find where value is exact.
Using LIKE is not a perfect option since it will take all rows which contains 1, using = also is not a option since it searches for equal value.
Also tried to use INSTR, but it works almost same as LIKE.
Same with Locate.
There is currently stored formats:
number (example: "2" without "")
number. (example: "2." without "")
number.number (example: "2.23.52.12.35" without "")
And they don't change.
This column only stores numbers, no letter or other type of string ONLY numbers (integer type)
Is there any way to strictly search for value?
My database is InnoDB. Thank you for your time.
Try using REGEXP:
SELECT *
FROM yourTable
WHERE CONCAT('.', StringB, '.') REGEXP CONCAT('[.]', '2', '[.]');
Demo
We could also use LIKE instead of REGEXP:
SELECT *
FROM yourTable
WHERE CONCAT('.', StringB, '.') LIKE CONCAT('%.', '2', '.%');
If you do:
where stringB = 1
Then MySQL has to figure out what types to use. By the rules of SQL, it will convert '1.00' to a number -- and they match.
If you do
where stringB = '1'
Then the types do what you intend. And the values are compared as strings.
More: Keep the types consistent. Don't ever depend on implicit conversion.

MySql : query to format a specific column in database table

I have one column name phone_number in the database table.Right now the numbers stored in the table are format like ex.+91-852-9689568.I want to format it and just want only digits.
How can i do it in MySql ? I have tried it with using functions like REGEXP but it displays error like function does not exist.And i don't want to use multiple REPLACE.
One of the options is to use mySql substring. (As long as the format doesn't change)
SELECT concat(SUBSTRING(pNo,2,2), SUBSTRING(pNo,5,3), SUBSTRING(pNo,9,7));
if you want to format via projection only, use SELECT, you will only need to use replace twice and no problem with that.
SELECT REPLACE(REPLACE(columnNAme, '-', ''), '+', '')
FROM tableName
otherwise, if you want to update the value permanently, use UPDATE
UPDATE tableName
SET columnName = REPLACE(REPLACE(columnNAme, '-', ''), '+', '')
MySQL does not have a builtin function for pattern-matching and replace.
You'll be better off fetching the whole string back to your application, and then using a more flexible string-manipulation function on it. For instance, preg_replace() in PHP.
Try the following and comment please.
Select dbo.Regex('\d+',pNo);
Select dbo.Regex('[0-9]+',pNo);
Reference on RUBLAR.
So MYSQL is not like Oracle, hence you may just use a USer defined Function to get numbers. This could get you going.

Extract Only charcters from a String

I have a column value like
lut00006300.txt
sand2a0000300.raw
I need to extract only character data from above given column values. I tried the below query and was able to get the first three characters.
select filesize,
substring(Filename FROM 1 FOR 3) AS Instrument from Collection;
Is there any approach to extract only the characters from the column value leaving the extensions
The results should be :
LUT
SAND2A
I think below query will helps you.
select filesize,Filename from Collection where Filename REGEXP '[:alpha]';
Refer:- http://dev.mysql.com/doc/refman/5.1/en/regexp.html
SELECT
filesize,
UPPER(SUBSTRING_INDEX(SUBSTRING_INDEX(Filename, '.', 1), '0', 1)) AS Instrument
FROM Collection;
This is a dirty solution, since you want to have the 2 in SAND2A.
Read more about the functions here.

Replace value within a comma-delimited string in MySQL?

Suppose I have the following comma-delimited column value in MySQL: foo,bar,baz,bar,foo2
What is the best way to replace whatever is in the 4th position (in this case bar) of this string with barAAA (so that we change foo,bar,baz,bar,foo2 to foo,bar,baz,barAAA,foo2)? Note that bar occurs both in position 2 as well as position 4.
I know that I can use SUBSTRING_INDEX() in MySQL to get the value of whatever is in position 4, but have not been able to figure out how to replace the value in position 4 with a new value.
I need to do this without creating a UDF or stored function, via using only the standard string functions in MySQL (http://dev.mysql.com/doc/refman/5.5/en/string-functions.html).
Hmm... maybe this?
SELECT #before := CONCAT(SUBSTRING_INDEX(`columnname`,',',3),','),
#len := LENGTH(SUBSTRING_INDEX(`columnname`,',',4)+1
FROM `tablename` WHERE ...;
SELECT CONCAT(#before,'newstring',SUBSTRING(`columnname`,#len+1)) AS `result`
FROM `tablename` WHERE ...;
Replace things as needed, but that should just about do it.
EDIT: Merged into one query:
SELECT
CONCAT(
SUBSTRING_INDEX(`columnname`,',',3),
',newstring,',
SUBSTRING(`columnname`, LENGTH(SUBSTRING_INDEX(`columnname`,',',4)+1))
) as `result`
FROM `tablename` WHERE ...;
That +1 may need to be +2, I'm not sure, but that should work.
You first split your problem in two parts:
locate the comma and split the string in values separated by comma.
update the table with same string and some substring appended.
For the first part I would suggest you take a look here
And for the second part you should take a look here
One more thing there is no shortcut to any problem. You should not run from the problem. Take it as a challenge. Learn while you search for the answer. Best thing take guidance from here and Try to do more researching and efforts.
Try this:
UPDATE yourtable
SET
categories =
TRIM(BOTH ',' FROM
REPLACE(
REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
)
WHERE
FIND_IN_SET('2', categories)
taken from here The best way to remove value from SET field?