SQL中如何通过表关联条件更新列值
问题:根据关联邮箱更新表中custId字段值
原始数据表
table1
| id | name | |
|---|---|---|
| 1 | Zack | zack@email.com |
| 2 | Adam | adam@email.com |
| 3 | Billy | billy@email.com |
table2(已新增custId列,默认值为0)
| id | custId | |
|---|---|---|
| 1 | 0 | zack@email.com |
| 2 | 0 | adam@email.com |
| 3 | 0 | billy@email.com |
需求:将table2的custId列值更新为table1中对应邮箱的id值。
错误的尝试SQL
REPLACE INTO table2(custId) SELECT table2.id FROM table1, table2 WHERE table1.email = table2.email
错误执行结果
| id | custId | |
|---|---|---|
| 1 | 0 | zack@email.com |
| 2 | 0 | adam@email.com |
| 3 | 0 | billy@email.com |
| 4 | 1 | NULL |
| 5 | 2 | NULL |
| 6 | 3 | NULL |
期望的正确结果
| id | custId | |
|---|---|---|
| 1 | 1 | zack@email.com |
| 2 | 2 | adam@email.com |
| 3 | 3 | billy@email.com |
正确的SQL实现方法
方法1:UPDATE JOIN(MySQL等支持该语法的数据库)
这种方式效率较高,适合批量更新:
UPDATE table2 JOIN table1 ON table2.email = table1.email SET table2.custId = table1.id;
方法2:子查询(通用语法,多数数据库兼容)
如果数据库不支持JOIN更新,可以用子查询方式:
UPDATE table2 SET custId = ( SELECT id FROM table1 WHERE table1.email = table2.email );
内容的提问来源于stack exchange,提问作者Parama Artha
相关产品推荐
相关产品推荐

