Let's say I have a column value of '1|2|3|4|5'. These values are a string representation of an array, and I'd like to remove a single value in the string (by integer) resulting in '1|2|4|5'. What is the most efficient way in MySQL to do that given that the integer to be removed could be anywhere in the string?
You could use something like this:
UPDATE yourtable
SET col = TRIM(BOTH '|' FROM REPLACE(
REPLACE(
CONCAT('|',REPLACE(col, '|', '||'), '|'),
'|3|', '')
, '||', '|')
)
Here I double every | to ||, I then add a | at the beginning and one at the end. This way, every element has its own | at the start and | at the end.
Now we can safely replace |3| with an empty string.
We now need to convert double || back to |, and trim the string to eventually remove the | at the beginning and the one at the end.
See it working here.
If you are sure that element 3 cannot be present more than once, you can skip doubling | to ||, and you have to replace |3| with |. The rest is the same.
update table set col=replace ( col, '3','')
This will do a case sensitive search on the column. If its a huge table, have an index on this column. Results will be reasonably fast.
Related
I have a table which contains two fields. The first is name of type string. The second contains one or more strings separated by comma (but it can contain a single string with no commas at all)
I want to construct a query to know if the string in the name field does not exist in every comma separated strings in the names field.
Example 1:
---------------------------------------------------------
name names
---------------------------------------------------------
myname xmyname,myname,mynamey
All the comma separated strings contain the word myname. So the query shoudl not return this row.
But, Example 2:
---------------------------------------------------------
name names
---------------------------------------------------------
myname x,myname,mynamey
Should be returned. Because x does not contain myname.
The condition is that, if the string in the field name does not exists in each of the comma separated strings in the names field, then return the row.
This is not correct as this query will not return true in example 2 (which contains x which does not contain myname).
IMPORTANT NOTE:
1) There is not limit of how many commas there. It can be 0 commas or more. How to deal with this?
2) The strings are variables. It is not always the case that the string is myname. Each row contains a different string in the name field.
Try this regular expression:
where not concat(names, ',') regexp replace('^([^,]*{n}[^,]*,)*$', '{n}', name)
db-fiddle demo
How to read the pattern:
The inner pattern [^,]*{n}[^,]*, means
Any non comma character [^,] repeated any number of times (* means no times or multiple times).
followed by the value of the column name ({n} is a placeholder and will be replaced with the actual value using the replace() function)
followed by any non comma character [^,] repeated any number of times
followed by a comma
The outer pattern ^({inner_pattern})*$ means
Start of the string (^)
followed by the inner pattern repeated any number of times
followed by end of string ($)
To make this work, a comma is appended to the names column (concat(names, ',')), so that every element in the string ends with a comma.
The pattern will ensure, that any element in the comma separated string contains the value of the name column. Since you want the opposite result, we use where not ...
Assuming "myname" does not appear twice between two commas, you can count the commas and "myname"s:
where (length(names) - length(replace(names, ','))) >=
length(names) - length(replace(names, 'myname', '12345'))
This answer started off giving an incorrect REGEXP solution. But the best thing to do here would be to fix your data model, such that each name in the names column is actually on a separate row:
name | names
myname | xmyname
myname | myname
myname | mynamey
somename | x
somename | myname
somename | mynamey
Now we can do a simple aggregation query to answer your question:
SELECT name
FROM yourTable
GROUP BY name
HAVING COUNT(CASE WHEN names NOT LIKE CONCAT('%', name, '%') THEN 1 END) > 0;
Demo
You can approach this using the following SQL query
SELECT
name, names
FROM
`tablename`
WHERE
(LENGTH(names) - LENGTH(REPLACE(names, ',', '')) + 1)
=
ROUND (
(
LENGTH(names)
- LENGTH( REPLACE ( names, name, "") )
)/ LENGTH(name)
);
Explanation:-
This Will give you how many words are separated with ,
(LENGTH(names) - LENGTH(REPLACE(names, ',', '')) + 1) -
Following is matching the name in each row and returning how many times it found
ROUND (
(
LENGTH(names)
- LENGTH( REPLACE ( names, name, "") )
) / LENGTH(name)
)
DEMO
I have a database with TV Guide data, and in my description field (VARCHAR) sometimes i have a '|' where behind it is the rating. I used to check this in php, before converting it all to XML, but i would like to do this in SQL.
So if i have this string:
This is the description | rating pg-13
Then i want to keep the
This is the description
but if there is no '|' i want the whole string.
I tried using substring, but can't get it to work.
My query now is:
SELECT *, SUBSTRING(`long_description`, 1, POSITION('|' IN `long_description`)) FROM `programs` WHERE station_id = 1
this works only one way - this gives me the string before the '|' but if there is no '|' it gives an empty column.
Based on the use of backticks, you might be using MySQL. If so, substring_index() does exactly what you want:
select substring_index(long_description, '|', 1)
How about this:
SELECT
*,
IF(long_description LIKE '%|%',
SUBSTRING(`long_description`,
1,
POSITION('|' IN `long_description`)),
long_description)
FROM
`programs`
WHERE
station_id = 1
The IF clause basically just checks if you have a | in the field and applies your routine when this is true. Else it will simply return the complete long_description value.
I have a column that contains a string of comma delimited values. I use FIND_IN_SET to query this column and it works fine until there is a space between the value and the ,. I cannot control the input. The only solution I have found that works is by running REPLACE on the column within the FIND_IN_SET function. Unfortunately this will remove all spaces and could return undesired results.
The blow example would return both row in the table as opposed to the first one only.
col1 | col2
carpet , foo, bar | myVal1
abc, 123 , car pet | myVal2
Query
SELECT FIND_IN_SET('carpet', REPLACE(col1, ' ', ''));
Is there a way of limiting this to only trim the space wither side of the ,
You could try replacing ,[ ] or [ ], with just comma:
SELECT
col1,
col2,
FIND_IN_SET('carpet', REPLACE(REPLACE(col1, ', ', ','), ' ,', ',')) AS output
FROM yourTable;
Demo
Note: This answers assumes that there would be at most one leading/trailing space around the commas, and that your actual data itself does not contain commas. If there could arbitrary amount of whitespace, this answer would fail. In that case, what you would really need is regex replacement. MySQL 8+ does support this, but a better bet would be to normalize your data and stop storing CSV data like this.
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
I have data stored in a comma-separated format and I would like to run a query so that the users are ordered by the second value in the column.
So for this sample data:
user | Data
________________________________________
player1 | 45471,2529,32196008193896,99
admin | 1136,2595,17760808279311,95
gamer | 13495,2432,32196008193896,98
________________________________________
The order would be (2595-2529-2432) which is admin => player1 => gamer.
As I mentioned in the comments, you should really try to avoid storing delimited lists like that.
However, you can write a query to parse out the second value by using the SUBSTRING_INDEX() function. This function takes a string, the delimiter character, and an integer whether or not to take from the left/right of the delimiter and for how many. In other words, to get everything left of the second comma, it would look like this:
SELECT SUBSTRING_INDEX(data, ',', 2)
FROM myTable;
Then, from that string, you want everything to the right of the first comma, so you'll have to nest the functions. (Note, this may hurt efficiency, but that's the downfall of delimited lists):
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(data, ',', 2), ',', -1)
FROM myTable;
Then, you can just order by that value:
SELECT *
FROM myTable
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(data, ',', 2), ',', -1) DESC;
Here is an SQL Fiddle example.