Getting a substring in a mysql query - mysql

In my mysql table, one of the fields holds data of the nature:
{"gateway":"somevalue","location":"http://www.somesite.org/en/someresource","ip":"100.0.0.9"}
I need to extract the value of the location attribute alone from this field, which is
http://www.somesite.org/en/someresource
in the this case. How do I write a query to achieve this?

Apart from the fact that you better off not storing delimited values of any form (including JSON) in the database, but rather normalize your data, you can leverage very handy SUBSTRING_INDEX() function in the following way
SELECT TRIM(BOTH '"' FROM SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '"location":', -1), ",", 1)) location
FROM table_name
WHERE ...

Related

MYSQL replace depending on comma position

If I have a value in column WorkoutID that looks like 100,10,7
and I want to remove the value 10 from this, I can use the following SQL script:
UPDATE
UserDB.Programs
SET
WorkoutID = REPLACE(WorkoutID, ',10','')
WHERE
ProgramID = '7172';
which would correctly output 100,7.
The expected outcome ALWAYS needs to be
number, number, or number
NOT number,,number, or number, or ,number
which makes it tricky because in the replace statement, i need to look for the value, but how can I assume the comma position? i.e replace(WorkoutID, ',10', ''), or replace(WorkoutID, '10,', '')
As others pointed out in the comment, you should not store comma separated values in a single column.
But in case you have no control over the data, here is a solution.
The problem with your solution is that you may unintentionally remove parts of other values, i.e. if you have something like 100,10,7,1000 and remove ,10, you will get 100,700...
One solution would be to add a leading and trailing comma to the original string, then replace the value enclosed with commas (i.e. ,10,), then remove the added leading and trailing commas.
Example :
CREATE TABLE program (ProgramID INT, WorkoutID TEXT);
INSERT INTO program VALUES (1, '100,12,4,55,120,212,45');
SELECT TRIM(BOTH ',' FROM REPLACE(CONCAT(',', WorkoutID, ','),',12,',','))
FROM program;
Result :
100,4,55,120,212,45
Fiddle
There may be other solutions using JSON paths etc. but I think this one is pretty fast and understandable.

MySQL query to delete all the random data between two known strings

I have a MySQl Database, the table name is "post_data" field name is "content_data"
I want to delete all the random data between two known strings.
i want to delete all text between 'www.OldDomain.com/' & '/www.NewDomian.com'
For example:
www.OldDomain.com/redirect?RandomTextUrl/www.NewDomian.com/txturl
any suggestion will be appreciated?
Assuming that each of these strings appears exactly once in content_data and in the correct order:
select concat(substring_index(content_data, 'www.OldDomain.com', 1),
'www.OldDomain.com',
'www.NewDomian.com',
substring_index(content_data, 'www.NewDomian.com', -1)
)
If you are looking to struggle and do it using MySQL You could use SUBSTRING_INDEX
I would suggest to use PHP/Java/C# or any other language to do these kinds of string parsing though.
You can use LOCATE and SUBSTRING functions to get the string between two desired strings.
SELECT SUBSTRING(
data,
LOCATE('www.OldDomain.com/', data) + LENGTH('www.OldDomain.com/'),
LOCATE('/www.NewDomain.com', data) - (LOCATE('www.OldDomain.com/', data) + LENGTH('www.OldDomain.com/'))
) as output
FROM TABLE_NAME;
NOTE: TABLE_NAME is your table name, data is your column name and output is the alias for the extracted data.
Sample Run
CREATE TABLE stack (data varchar(100));
INSERT INTO stack VALUES('www.OldDomain.com/redirect?RandomTextUrl/www.NewDomain.com/txturl');
INSERT INTO stack VALUES('BEFOREwww.OldDomain.com/redirect?RandomTextUrl/www.NewDomain.com/txturl');
INSERT INTO stack VALUES('www.OldDomain.com/redirect?RandomTextUrl/www.NewDomain.com/txturlAFTER');

how to skip the inverted commas when selecting a column from MySQL

There is a table with fields name, age, city and state. Now I need to select rows based on city name. The value of the column city is surrounded with ", for example "LA".
How can I write a SELECT statement for getting data based on city.
\" is the escape combination for double quotes:
SELECT * FROM mytable WHERE city = '\"LA\"';
See MySQL documentation "String Literals".
Just suggestion, if you are collecting and storing the information in the table to be queried later (ie you are in control of the input), try to clean the data up before storing it to make it easier to query?
If the input has quotes and white space, clean that before inserting the values into the table. Use programming to do this, or mySQL: TRIM() and REPLACE() to remove the characters that might make a query hard to build and then store the resulting value into the table.
Of course, if you do not have control of the input data, that is where the answers above and the challenge to a programmer begins, trying to figure out the different input possibilities and dealing with that.
SELECT *
FROM table1
WHERE city LIKE '%LA%'
or
SELECT *
FROM table1
WHERE city REGEXP '^[[:space:]]*LA[[:space:]]*$'

Trim leading zeros in comma separated values in a column

Ex.Table Store
store_id Employee_id
0020,0345,0002345 0234
0034 0943
I tried REPLACE(LTRIM(REPLACE(store_id,'0',' ')),' ','0') but it trims leading zeros for the first value alone.
How to get all storeIds of an employee without leading zeros in a sql query?
Is it possible?
If this is a table in an rdbms, it violates 1NF. You should avoid doing this. If you possible use junction tables or reference tables. Else you could use the same schema and insert multiple entries corresponding to a single Employee_id.
Now, To solve this in a generic manner, there is only one solution, UDF's. User defined function specification is here
or move this kind of processing to the client.
If you just want to remove the leading zeros -- and there aren't too many -- you can use replace():
select substr(replace(replace(replace(concat(',', store_id), ',0', ','),
',0', ','),
',0', ',')
2, length(store_id)
This just replaces a comma followed by a zero with a comma, adding and removing a comma at the beginning and end of the string. Different databases have slightly different names for substr() and length(), but the functionality is generally there.

How do I convert a string of words into multiple rows of a Table using MySql command Line

I have a string such as,
"This is a sting and I dont know how long I am"
I want to turn every word in string into a row for my sql table so that I get:
ThisIs a string and I dont know etc...
I need to be able to do this with the MySql command line. (I also need an adjacent column to all be filled with ones on every row, incase that helps/changes your answer) I was thinking I could somehow use INSERT String (Words, num) Values (#words, 1) but I dont know how to get it to add every word. Is there any easy way to do this? If not, how would it be done?
MySQL does not have a function to split a delimited string. This problem is heavily discussed on MySQL manual page (search "split"), although there is no direct solution to handle variable number of elements.
Instead of that, I would help myself to generate such a query:
SELECT CONCAT('INSERT INTO t1 VALUES ("', REPLACE(REPLACE(TRIM(string_column), '"', '\\"'), ' ', '", "'), '")') FROM t2_with_string