1

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

例如:

表 1 包含以下字段:
email, title, first_name, last_name, (+ others)

表 2 包含以下字段:
email, title, first_name, last_name, modified, (+ others)

我想将title, first_name, last_namefrom复制table2table1where table1.email = table2.email

所以table2保存了所有数据,我想将这些数据复制到table1电子邮件与 intable1匹配的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新记录。

4

1 回答 1

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
于 2013-05-31T08:42:29.433 回答