简体   繁体   English

如何通过与另一个表联接来更新MySQL表列

[英]How to update MySQL table column by joining with another table

I have 2 MySQL tables. 我有2个MySQL表。

Table_1 (to be updated): 表_1(待更新):

ID LINK NEW_ID
 1 4866
 2 1790
 3 7723

Table_2 (to be joined): 表_2(将要加入):

ID LINK
47 1790
49 4866
51 7723

I want to update Table 1 by adding the ID from Table 2 into the "NEW_ID" column. 我想通过将表2中的ID添加到“ NEW_ID”列中来更新表1。 There is a reason for it rather than have the tables joined going forward. 这是有原因的,而不是将表联接在一起。

I tried a couple of MySQL queries, the latest of which looks like this. 我尝试了几个MySQL查询,其中的最新查询如下所示。 I get errors with it. 我有错误。

$query_string = '
  UPDATE Table_1
  SET NEW_ID = (
    SELECT Table_2.ID
    FROM Table_2
    LEFT JOIN Table_1 ON Table_1.LINK = Table_2.LINK
  )
';
mysqli_query( $GLOBALS['db_link'], $query_string ) or die( mysqli_error( $GLOBALS['db_link'] ) );

Error You can't specify target table 'Table_1' for update in FROM clause 错误您无法在FROM子句中指定目标表“ Table_1”进行更新

UPDATE Table_1 a
JOIN Table_2 b
   ON a.LINK = b.LINK
set a.NEW_ID = b.ID
where a.LINK=b.LINK;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM