【问题标题】:how do I update table1 values (select from table2) where table1.email = table2.email如何更新 table1 值(从 table2 中选择)其中 table1.email = table2.email
【发布时间】:2013-05-31 08:32:46
【问题描述】:

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

例如:

表 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 中的电子邮件与table2 中的FIRST 'most recent (by 'modified')' email found 匹配(所以最近修改的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 一个新记录。

【问题讨论】:

  • 也许你需要更新?
  • 您要更新实际值还是插入新值?
  • 为什么会收到ERROR: Unknown column 'table1.email' in 'where clause'? table1 中的电子邮件列?

标签: mysql select insert


【解决方案1】:

试试这个查询 -

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

【讨论】:

  • 最后修改的电子邮件条件在哪里?
  • @RAS 我很快就会添加新的查询。
  • 第二个查询查找最近的数据。也试试吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-28
相关资源
最近更新 更多