MYSQL-根据是否为空将值追加或插入到列中 [英] MYSQL - append or insert value into a column depending on whether it's empty or not

查看:157
本文介绍了MYSQL-根据是否为空将值追加或插入到列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我试图将string附加到表中的VARCHAR列中. 字符串类似于"//string",稍后将使用正斜杠将字符串分解为PHP中的数组. 我想知道在MySQL中是否有一种方法 如果列为空,则执行CONCAT(columnname, "//string"),否则执行普通的UPDATE ... SET ... WHERE.这样,我就可以避免将来爆炸的字符串的 第一个 值成为带有前斜杠的"//string".

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();

然后让PHP决定执行哪个操作:

and then leave PHP decide which operation perform:

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

但是由于2x数据库调用和更多的PHP代码,这将浪费时间/资源.

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

谢谢.

推荐答案

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

这意味着您的情况:

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');

这篇关于MYSQL-根据是否为空将值追加或插入到列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆