我的数据库中有2个表。
表#1
-------------------------------------------------------------------------
| name | family | phone | email | gender | phone2 | address | birthdate |
-------------------------------------------------------------------------
表#2
-----------------------------------------
| gender | address | phone | birthdate |
-----------------------------------------
表#1中的列地址和phone2为空,列gender和birthdate值与表#2相同。
当性别和出生日期在每一行中相同时,如何从表#2中读取数据并使用表#2地址和电话列中的值更新表#1中的地址和phone2?
例如: 这是表#1中的一些数据
-------------------------------------------------------------------------
| name | family | phone | email | gender | phone2 | address | birthdate |
-------------------------------------------------------------------------
| john | doe | 12345| t@t.com| Male | | | 1980-01-01|
-------------------------------------------------------------------------
| mike | clark | 65432| x@y.com| Male | | | 1990-01-01|
-------------------------------------------------------------------------
| Sara | King | 875465| a@b.com|Female| | | 1970-01-01|
-------------------------------------------------------------------------
以下是表#2中的一些数据
-----------------------------------------
| gender | address | phone | birthdate |
-----------------------------------------
| Male | 1704test|0457852|1980-01-01 |
-----------------------------------------
| Female | 1705abcs|0986532|1970-01-01 |
-----------------------------------------
| Male | 1602cyzd|0326589|1990-01-01 |
-----------------------------------------
我想用表#2中的数据更新表#1并检查性别和生日,并使表#1像
-------------------------------------------------------------------------
| name | family | phone | email | gender | phone2 | address | birthdate |
-------------------------------------------------------------------------
| john | doe | 12345| t@t.com| Male |0457852 |1704test | 1980-01-01|
-------------------------------------------------------------------------
| mike | clark | 65432| x@y.com| Male |0326589 |1602cyzd| 1990-01-01|
-------------------------------------------------------------------------
| Sara | King | 875465| a@b.com|Female |0986532 |1705abcs| 1970-01-01|
-------------------------------------------------------------------------
我该怎么做?
答案 0 :(得分:3)
您可以在更新声明中使用JOIN
。
UPDATE t1
SET t1.phone2 = t2.phone, t1.address = t2.address
FROM table1 t1
JOIN table2 t2 on t1.gender = t2.gender and t1.birthdate = t2.birthdate