-1

I have a database with 2 tables. In table1 there are two column:

columnA (autoincrement) and columnB (text)

And in table2: columnC (autoincrement) and columnD (text)

I want to replace (copy) data in columnB with data from columnD only if the autoincrement columns are equals.

I tried with this, but its not correct:

UPDATE table1 
   SET columnB = (
      SELECT columnD 
      FROM table2 WHERE (
         SELECT columnA FROM table1 = SELECT columnC FROM table2)
Dharman
  • 30,962
  • 25
  • 85
  • 135
user348246
  • 380
  • 4
  • 16

3 Answers3

0

You can update it by an UPDATE with an INNER JOIN:

UPDATE `table1` as a
INNER join table2 b on a.columnA = b.columnC
SET a.`columnB` = b.`columnD`
-- WHERE clause if needed ...

See: SQL Server - inner join when updating

Community
  • 1
  • 1
leonard.javiniar
  • 539
  • 8
  • 25
-1

You can use left join: UPDATE table1 t1 left join table2 t2 on t1.columnA=t2.columnC set t1.columnB=t2.columnD where t2.columnc is not null

Jimish Gamit
  • 1,014
  • 5
  • 15
-1

You are trying to update columnB with one query, which means regardless of whether columnA and columnC are equal. I'd suggest creating a procedure, implementing the if statement there and then simply calling the procedure.