MySQL 使用 concat 更新和追加多行数据

标签 mysql

这是我从中提取的数据示例:

+-----+------------+---------+----------+------------+
| id  |    name    | carrier | tracking |    date    |
+-----+------------+---------+----------+------------+
| 123 | john smith |   UPS   | abcdefgh | 2018-06-22 |
| 123 | john smith |   USPS  | 12345678 | 2018-06-23 |
+-----+------------+---------+----------+------------+

我正在更新的表中每个 ID 只有一个记录(而我从中提取的表可以有多个),我试图让最终输出看起来像这样:

+-----+------------------------------------------+
| id  |               shipping_info              |
+-----+------------------------------------------|
| 123 | 6/22 - UPS abcdefgh 6/23 - USPS 12345678 |
+-----+------------------------------------------+

我有一个问题,我快到了:

update table1
set shipping_info = concat(
DATE_FORMAT(table2.date_time, '\n%c/%e - '),
table2.carrier,
table2.tracking)
where id = '123'

+-----+---------------------+
| id  |    shipping_info    |
+-----+---------------------|
| 123 | 6/22 - UPS abcdefgh |
+-----+---------------------+

所以我的问题是,当我运行更新时,它只用第一行数据更新表,但我还需要将它附加到第二行。

最佳答案

你应该 group_concat 连接的字符串,例如:

select id, group_concat(concat(date,'-' , carrier,'-', tracking))
from my_table 
group by id 

和更新

update my_update_table m
inner join (
   select id, group_concat(concat(date,'-' , carrier,'-', tracking)) my_col
   from my_table 
   group by id 
) t on m.id = t.id 
set m.shipping_info = t.my_col

关于MySQL 使用 concat 更新和追加多行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51138789/

相关文章:

mysql - 如何在 MySQL 字段中选择逗号分隔值的唯一值?

java - 我无法从 AsyncTask 获得结果?

mysql - 如果该状态已经存在于该表的另一个属性,则停止将该表的属性更新为特定状态

mysql - 在 Grails war 中几个小时后与数据库的连接丢失

PHP:WAITING时间,因此函数直到 x 分钟后才能执行

java - XML 解析到 MySQL 数据库

php - MySQL多列总计解决方案

asp.net - 从两个列表框控件插入表格

php - 如何使用 MySQL 将一条记录的值分解为多行?

php - 在选择标记 HTML PHP MySQL 中从数据库中获取值