简体   繁体   English

Mysql:将某些列从一行复制到另一行

[英]Mysql: copy certain columns from one row to another

Is there an easy way to as an example copy COL2 and COL3 from row with ID3 to row with ID2 and replace any existing value?有没有一种简单的方法可以将 COL2 和 COL3 从 ID3 行复制到 ID2 行并替换任何现有值?

ID---COL1---COL2---COL3
1.   A        B        C
2.   D        E        F
3.   G        H        I
4.   J        K        L

Use UPDATE with a self-join.UPDATE与自联接一起使用。

UPDATE yourTable AS t1
CROSS JOIN yourTable AS t2
SET t1.col2 = t2.col2, t1.col3 = t2.col3
WHERE t1.id = 2
AND t2.id = 3

This is a very primitive way of updating the desired row.这是更新所需行的一种非常原始的方式。 Considering that the table was declared as tab in the DB you can actually JOIN it with a subquery filtered from the table itself without using an ON and then setting your desired variables accordingly.考虑到该表在数据库中被声明为tab ,您实际上可以使用从表本身过滤的子查询JOIN它,而无需使用ON ,然后相应地设置所需的变量。

UPDATE  tab JOIN  (SELECT * FROM tab WHERE ID = 3) AS temp SET   tab.COL1 = temp.COL1, tab.COL2 = temp.COL2, tab.COL3 = temp.COL3 WHERE tab.ID = 2 

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

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