sql - 用另一个表列中的值更新和替换一个表列中的值
问题描述
我有 2 张桌子:
id | bsi | cell
1 | 45 | NULL
2 | 23 | 600-1167
3 | 47 |
4 | 89 | 501- -
5 | 98 | 603-5670
我想用 bsi 匹配两个表的另一个表中另一个列的数据替换单元格值
这是我的第二张桌子:
id | bsi | contact
1 | 45 | 610-5896
2 | 23 | 605-4567
3 | 47 | NULL
4 | 89 | 689-9089
5 | 98 | NULL
我希望第一个表中的每个值都替换为第二个表中的新值,以及两个表在 bsi 代码中匹配的值,即一旦第二个表中有一个值,用新值替换 NULL 和 '501- -' .
所以结果应该是一个更新的表,如下所示:
id | bsi | cell
1 | 45 | 610-5896
2 | 23 | 605-4567
3 | 47 | NULL
4 | 89 | 689-9089
5 | 98 | 603-5670
我已经尝试过这个查询,但它只替换了新值,并且似乎为 table1 而不是 table2 中的项目写入空值。我想保留表 1 但不是表 2 中的 table1 值。
UPDATE Table1
SET Table1.cell = Table2.Contact
FROM Table1 INNER JOIN Table1 ON Table1.bsi = Table2.bsi
解决方案
您的加入似乎有点偏离...您没有加入第二张桌子
UPDATE t1
SET t1.cell = t2.Contact
FROM Table1 t1
INNER JOIN Table2 t2 ON --changed to table2
t1.bsi = t2.bsi
--where <some condition>
此外,仅更新所有行比使用where clause
. 请参阅 Aaron Bertrand 对此的测试。我这样做是因为尽管您说我想保留 table1 中的值 table 1 但不是 table 2,但这并没有反映在您的预期输出中。如果您确实想有条件地更新它们,那么您需要添加where clause
.
create table table1 (id int, bsi int, cell varchar(16))
create table table2 (id int, bsi int, contact varchar(16))
insert into table1 values
(1,45,NULL),
(2,23,'600-1167'),
(3,47,''),
(4,89,'501- -')
insert into table2 values
(1,45,'610-5896'),
(2,23,'605-4567'),
(3,47,NULL),
(4,89,'689-9089')
UPDATE t1
SET t1.cell = t2.Contact
FROM Table1 t1
INNER JOIN Table2 t2 ON --changed to table2
t1.bsi = t2.bsi
--where <some condition>
select * from table1
回报
+----+-----+----------+
| id | bsi | cell |
+----+-----+----------+
| 1 | 45 | 610-5896 |
| 2 | 23 | 605-4567 |
| 3 | 47 | |
| 4 | 89 | 689-908 |
+----+-----+----------+
推荐阅读
- python - TypeError“输入类型不支持ufunc'isfinite'”
- reactjs - 如何使屏幕标题动态化?
- python - 如何指示哪只乌龟赢得了比赛
- puppet - 将多个 hiera.yaml 文件与 puppet 一起使用
- c# - 在二维矩阵中搜索特定位置 c# top-bottom, left-right
- corda - 交易对手将输入状态之一更新为交易的最佳方式是什么?
- java - 从文件读取和写入 Java
- javascript - 如何更改图像质量
- java - server.session.cookie.max-age 似乎不起作用
- html - 请协助我在我的网站上添加谷歌广告我试过他们没有显示