Solved: How to update the specified column data of all records in a certain table to the data of another column (the specified column of another table) with the SQL statement?

Problem phenomenon:

Today I thought of a requirement like this. How to update the specified column data of all records in a certain table to another column (the specified column of another table) with a SQL statement?


problem analysis:

The requirements from the problem can be exemplified as follows:

The first type:  If there is now a table T  containing multiple fields including id and t_id

Now wants  table T  in  all records  the id field data of this row, modify  table T of t_id field  data in this row;

(That is, each record of the value of the id field is modified to  a value t_id field )

The second type: if there are two tables A, B  : Among them, the  A table  contains the id field , but does not contain the  t_id field; the  B table  contains the  id and t_id fields ;

Now wants to  Table A  in  all records  the id field data of this row, modify  Table B of t_id field  data in this row;

(I.e. the  A table  each record of the value of the id field modified as  Table B in the value field t_id )

 

In the study and work of the above two situations, many small partners will encounter; here we first analyze the situation of these two situations:

1. The first is that there are already two fields ( id and t_id ) in a single table, so you only need to do an update operation based on a single table ;

2. The second type needs to operate two tables, because table A does not have a  t_id field, and the two tables must be related ( A and B tables have id fields, and all the ids in A can be found in B ) To be modified successfully.


Solution:

The first type (single table operation): execute the following code:

update T

set id = t_id

 

The second type (multi-table operation): The code is as follows:

update A

set id = B.qx_id (或 set A.id = B.qx_id )

from B

where A.id = B.id 

 

Guess you like

Origin blog.csdn.net/weixin_42585386/article/details/108647024