A
A
Andrey Galko2016-02-20 19:30:28
MySQL
Andrey Galko, 2016-02-20 19:30:28

How to replace only the first occurrence in a string?

I need to perform an UPDATE of the row and delete the first occurrence of "11" from the parent field with the value "14 11 10 11 52" (this is an approximate value, in fact, it will be any at all), and leave the second and subsequent ones untouched. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2016-02-20
@McDeFF

-- строка, в которой нужно провести поиск
SET @parent = '14 11 10 11 52';
-- строка, которую нужно найти
SET @search = '11';

-- найти начальную позицию нужной строки
SELECT INSTR(@parent, @search);

-- зная расположение и размер подстроки, можно вырезать фрагмент текста
-- первая часть
SELECT SUBSTR(@parent, 1, INSTR(@parent, @search) - 1);
-- хвост
SELECT SUBSTR(@parent, INSTR(@parent, @search) + LENGTH(@search));

-- все вместе
SELECT CONCAT
(
  SUBSTR(@parent, 1, INSTR(@parent, @search) - 1), 
  SUBSTR(@parent, INSTR(@parent, @search) + LENGTH(@search))
);

A rough version with UPDATE will be something like this (it’s better to make a procedure and / or pass the search string through a parameter):
UPDATE example SET parent = CONCAT
(
  SUBSTR(parent, 1, INSTR(parent, '11') - 1), 
  SUBSTR(parent, INSTR(parent, '11') + LENGTH('11'))
);

I
Igor, 2016-02-20
@unitby

In MariaDB you can use the following code

SELECT REGEXP_REPLACE('14 11 10 11 52 11 11 78 65', '(11.)(.*$)', '\\2')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question