mysql:将字符串连接到列

时间:2015-03-07 17:56:59

标签: php mysql sql mysqli

我试图在"消息中添加新消息"列,以便将历史记录保存在一个位置。我能够使用新消息更新字段,但我无法将它们连接起来。你能帮忙吗?

这是我的代码:

$stmt = mysqli_prepare($mysqlCon, "INSERT  INTO history (`phone`, `message`) VALUES (?, ?) 
ON DUPLICATE KEY SET message = CONCAT(message,VALUES(message));");

mysqli_stmt_bind_param($stmt, 'ss', $phone, $message);

$phone= $_POST['from'];
$message = $_POST['message'];

编辑:为什么投票没有解释?

1 个答案:

答案 0 :(得分:1)

MySQL 5.6.14:

使用:

insert into history (phone, message) 
values (1, 'test') 
on duplicate key 
    update message = concat(message, values(message));

我们举一个例子:

CREATE TABLE `history` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `phone` int(11) DEFAULT NULL,
  `message` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB;

让我们添加初始数据:

insert into history (phone, message) values (1, 'test');

+----+-------+---------+
| id | phone | message |
+----+-------+---------+
|  1 |     1 | test    |
+----+-------+---------+

让我们使用on duplicate key字词再次添加set

insert into history (phone, message) values (1, 'test') on duplicate key set message = concat(message, values(message));

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set message = concat(message, values(message))' at line 1

让我们使用on duplicate key字词再次添加update

insert into history (phone, message) 
values (1, 'test') 
on duplicate key 
     update message = concat(message, values(message));

Query OK, 2 rows affected (0.01 sec)

+----+-------+----------+
| id | phone | message  |
+----+-------+----------+
|  1 |     1 | testtest |
+----+-------+----------+

希望这个例子有所帮助。