There are often requests to replace or add the data in a field in table A with table B according to the query conditions. At this time, I generally use update statement and EXISTS to make a modification.
User A table
Id | Dictionary encoding | status |
---|---|---|
0001 | 0 | |
0002 | 4402 | 1 |
0003 | 0 |
dd
address B table
Primary key Id | code | name | userId |
---|---|---|---|
1 | 4400 | Beijing | 0001 |
2 | 4401 | Shanghai | 0002 |
3 | 4401 | Shanghai | 0003 |
Now we need to replace all the data in table a with the state of 0 and the dictionary code being empty with the code in table B
update A set 字典编码 = (select code from B where userId = id)
where EXISTS(select 1 from B where userId = id and 状态 =0 and 字典编码 is null)
The first query of table B is to match the data of table B with table A. The query after EXISTS is to screen out the data that needs to be modified, so that the data that needs to be modified can be queried accurately.