MYSQL-根据是否为空将值追加或插入到列中 [英] MYSQL - append or insert value into a column depending on whether it's empty or not
问题描述
正如标题所说,我试图将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屋!