¿Cómo anteponer una cadena a un valor de columna en MySQL?


Necesito una instrucción SQL update para actualizar un campo particular de todas las filas con una cadena "test" que se agregará al frente del valor existente.

Por ejemplo, si el valor existente es "try" debería convertirse en "testtry".

Author: Spontifixus, 2009-03-25

5 answers

Puedes usar la función CONCAT para hacer eso:

UPDATE tbl SET col=CONCAT('test',col);

Si desea obtener más inteligente y solo actualizar las columnas que no tienen la prueba antepuesta, intente

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';
 228
Author: Paul Dixon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 10:06:59
UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...]
 15
Author: Ferdinand Beyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 09:18:43

Eso es simple

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);
 6
Author: soulmerge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 09:25:27

Muchas funciones de actualización de cadenas en MySQL parecen estar funcionando así: Si un argumento es null, entonces la concatenación u otras funciones devuelven null también. Por lo tanto, para actualizar un campo con el valor null, primero establezca un valor no nulo, como ''

Por ejemplo:

update table set field='' where field is null;
update table set field=concat(field,' append');
 5
Author: bvidinli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-04 13:57:38
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column1) donde 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2) donde 1
  • UPDATE table_name SET Column1 = CONCAT('newtring', table_name.Column2, 'newtring2') donde 1

Podemos concat misma columna o también otra columna de la tabla.

 0
Author: user3419778,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-14 12:41:40