我试图将一些数据从一个表复制到另一个表,其中电子邮件地址是相同的。
例如:
表1有字段:
email, title, first_name, last_name, (+ others)
表2有字段:
email, title, first_name, last_name, modified, (+ others)
我想将title
,first_name
,last_name
从table2
复制到table1
table1.email = table2.email
。
因此table2
包含我要复制到table1
的所有数据,其中table1
中的电子邮件与FIRST 'most recent (by 'modified')' email found
中的table2
匹配(所以最新修改的datetime
)。
我正在尝试这样的事情:
INSERT INTO `table1` (title, first_name, last_name)
SELECT title, first_name, last_name from `table2`
WHERE table1.email = table2.email
ERROR: Unknown column 'table1.email' in 'where clause'
基本上,我在一个声明中需要这样的东西..
SELECT EMAIL as `originalEmail` FROM `table1`
SELECT title, first_name, last_name FROM `table2`
WHERE table2.email = table1.email
ORDER BY `modified` desc # Get the most recently modified
LIMIT 1 # limit to 1 result (the most recent one)
UPDATE `table1` (title, first_name, last_name) values (*values from above*)
WHERE EMAIL = `originalEmail`
编辑
- 我想UPDATE
而不是INSERT
新记录。
答案 0 :(得分:5)
尝试此查询 -
UPDATE `table1` t1
JOIN `table2` t2
ON t1.email = t2.email
SET
t1.title = t2.title,
t1.first_name = t2.first_name,
t1.last_name = t2.last_name
使用最新条件查询table2
条记录 -
UPDATE `table1` t1
JOIN (SELECT * FROM `table2` GROUP BY email ORDER BY modified DESC) t2
ON t1.email = t2.email
SET
t1.title = t2.title,
t1.first_name = t2.first_name,
t1.last_name = t2.last_name