简体   繁体   English

如何在UPDATE查询MYSQL中合并具有相同ID的两行

[英]How to combine two rows with the same id in an UPDATE query MYSQL

I have a table with addresses and postcodes in different rows but linked by an id column. 我有一个表,其中的地址和邮政编码在不同的行中,但由id列链接。

CURRENT STATE 当前状态

id addressLabel addressValue id addressLabel addressValue
22 home address xxxxx 22 home address xxxxx
22 home postcode yyyy yyyy 22 home postcode yyyy yyyy

DESIRED STATE 期望状态

id addressLabel addressValue id addressLabel addressValue
22 home address xxxxxx, yyyy yyy 22 home address xxxxxx, yyyy yyy

I want to concatenate the two rows with the same id into the addressValue column with a comma separator (then delete the postcode). 我想用逗号分隔符将具有相同ID的两行连接到addressValue列中(然后删除邮政编码)。 I have seen plenty of examples using SELECT but I can't see how they would work with UPDATE. 我已经看到了许多使用SELECT的示例,但看不到它们如何与UPDATE一起使用。

You can use a selfjoin in the UPDATE statement: 您可以在UPDATE语句中使用自联接:

update mytable a
join mytable p using(id)
set a.addressValue = concat(a.addressValue, ', ', p.addressValue)
where a.id = 22
  and a.addressLabel = 'home address'
  and p.addressLabel = 'home postcode';

delete from mytable
where id = 22
  and addressLabel = 'home postcode';

Demo: http://sqlfiddle.com/#!9/649ef3/1 演示: http : //sqlfiddle.com/#!9/649ef3/1

Remove the conditions id = 22 if you want to affect the full table. 如果要影响整个表,请删除条件id = 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM