简体   繁体   中英

How to update MySQL table column by joining with another table

I have 2 MySQL tables.

Table_1 (to be updated):

ID LINK NEW_ID
 1 4866
 2 1790
 3 7723

Table_2 (to be joined):

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. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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