这是我从中提取的数据示例:
+-----+------------+---------+----------+------------+
| 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/