MYSQL - append or insert value into a column depen

2020-08-04 05:08发布

问题:

As title says, im trying to append a string to a VARCHAR column in my table. The string is something like " //string ", forward slashes will be used later to explode the string to an array in PHP. I was wondering if there's a way in MYSQL to perform a CONCAT(columnname, "//string") if the column is empty, otherwise perform a normal UPDATE ... SET ... WHERE . In this way, i will avoid the first value of my future exploded string to be a "//string" with forward slahes.

also, above I 've used bold characters for "in MYSQL" because I know i could first query the DB (to check if the column is empty) with something like:

$q = $conn->dbh->prepare('SELECT columnname FROM tablename WHERE username=:user');
$q->bindParam(':user', $username);
$q->execute();
$check = $q->fetchColumn();

and then leave PHP decide which operation perform:

if ($check != '') { // PERFORM A CONCAT }
else { // PERFORM AN UPDATE }

but this would mean a waste of time/resources due to 2x database calls and more PHP code.

thanks.

回答1:

https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

That means in your case:

INSERT INTO tablename (id,columnname) VALUES (1,'//string')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');

http://sqlfiddle.com/#!9/bd0f4/1

UPDATE Just to show you your options:

http://sqlfiddle.com/#!9/8e61c/1

INSERT INTO tablename (id, columnname) VALUES (1, '//string')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');

INSERT INTO tablename (id, columnname) VALUES (1, '//string')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');

INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='blahblah'), '//string')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');

INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE id=2), '//string')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');

INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='newone'), '//newone')
  ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//newone');


回答2:

If what you want is this:

first string: column will contain 'firststring'

second string: column will contain 'firststring//secondstring'

then do the update like this:

UPDATE tablename SET columnname = CONCAT( IF(IFNULL(columnname,'')='','',CONCAT(columnname,'//')), :string) WHERE username=:user