如何在Teradata中通过Join更新Transaction_table的Cust_Num与Cust_Ind
问题:基于SSN匹配更新交易表字段
现有表结构
Transaction_table(交易表)
| Date | SSN | Cust_Num | Cust_Ind |
|---|---|---|---|
| 1/1/21 | 111-1111 | null | null |
| 1/2/21 | 222-2222 | null | null |
| 1/3/21 | null | null | null |
Customer_table(客户表)
| Date | SSN | Cust_Num | Cust_Name |
|---|---|---|---|
| 1/1/21 | 111-1111 | 101 | Adam |
| 1/2/21 | 222-2222 | 102 | Bobby |
| 1/3/21 | 333-3333 | 103 | Carter |
需求
当两张表的SSN字段相等时,用Customer_table的Cust_Num更新Transaction_table的Cust_Num字段,同时将Transaction_table的Cust_Ind字段设置为'SSN Match'。
报错的尝试代码
Update t from Transaction_table as t, Customer_table as src set t.Cust_Num = src.Cust_Num, t.Cust_ind = 'SSN_Match' where t.SSN = src.SSN
解决方案
你的代码问题在于多表更新的语法不符合对应数据库的规范,不同数据库的多表更新语法存在差异,以下是主流数据库的正确写法:
1. SQL Server 写法
UPDATE t SET t.Cust_Num = src.Cust_Num, t.Cust_Ind = 'SSN Match' FROM Transaction_table t INNER JOIN Customer_table src ON t.SSN = src.SSN;
2. MySQL 写法
UPDATE Transaction_table t JOIN Customer_table src ON t.SSN = src.SSN SET t.Cust_Num = src.Cust_Num, t.Cust_Ind = 'SSN Match';
3. PostgreSQL 写法
UPDATE Transaction_table t SET Cust_Num = src.Cust_Num, Cust_Ind = 'SSN Match' FROM Customer_table src WHERE t.SSN = src.SSN;
注意事项
- SQL中
NULL = NULL的结果为未知,因此Transaction_table中SSN为NULL的记录不会被更新,符合需求逻辑 - 若
Customer_table中存在同一SSN对应多条记录的情况,需额外处理(比如取最新日期的记录),否则可能导致更新结果不确定
内容的提问来源于stack exchange,提问作者PandaMomma
相关产品推荐
相关产品推荐

