如何更新table1.email = table2.email的table1值(从table2中选择)

时间:2013-05-31 08:32:46

标签: mysql select insert

我试图将一些数据从一个表复制到另一个表,其中电子邮件地址是相同的。

例如:

表1有字段:
email, title, first_name, last_name, (+ others)

表2有字段:
email, title, first_name, last_name, modified, (+ others)

我想将titlefirst_namelast_nametable2复制到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新记录。

1 个答案:

答案 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