153

I have two tables...

table1 ( id, item, price ) values:

id | item | price
-------------
10 | book | 20  
20 | copy | 30   
30 | pen  | 10

....table2 ( id, item, price) values:

id | item | price
-------------
10 | book | 20
20 | book | 30

Now I want to:

update table1 
   set table1.Price = table2.price 
 where table1.id = table2.id
   and table1.item = table2.item.

How do I do it?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
niceApp
  • 2,913
  • 8
  • 35
  • 36

2 Answers2

305

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
Frost10000
  • 21
  • 8
RageZ
  • 26,800
  • 12
  • 67
  • 76
  • 4
    It gives me error message: invalid object table1. – niceApp Nov 17 '09 at 03:17
  • 4
    It gives me error The multi-part identifier "table1.price" could not be bound. – niceApp Nov 17 '09 at 03:23
  • make sure you don't use `Table1` but `table1` MSSQL seems to be case sensitive. – RageZ Nov 17 '09 at 03:41
  • It working fine for me but if I'm using aliasing it's not working in SQL Server 2008 like `update table1 set a.Price = b.price FROM table1 a INNER JOIN table2 b on a.id = b.id ` Error: The multi-part identifier "a.Price" could not be bound – Sam Feb 27 '15 at 13:07
  • 1
    @Sam, that is because you are referencing table1 in the UPDATE and FROM clauses (the same table is referenced twice). According to the script you are actually updating the field in the table you are querying rather than the one you are updating. The SET clause should reference the UPDATE table i.e. `UPDATE table1 SET price = b.price FROM (SELECT id, price AS p FROM table1) a INNER JOIN table2 b on a.id = b.id` – rjmd Jun 16 '15 at 08:38
  • 11
    it's not working in mysql – cikatomo Sep 30 '15 at 19:30
  • 1
    Not working in Access; gives missing operator error. – Zimano Apr 05 '16 at 17:17
  • 36
    For mysql: `UPDATE table1 INNER JOIN table2 ON table1.id = table2.id SET table1.Price = table2.price` can be used – rajthakur Mar 23 '17 at 07:23
  • 1
    you should not give table1.Price after SET, simply give column name Price. The example would work in postgres. `UPDATE table1 SET Price = table2.price FROM table1 INNER JOIN table2 ON table1.id = table2.id` – inquisitive May 02 '18 at 06:27
99

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);
Alexander
  • 23,432
  • 11
  • 63
  • 73
Nadeem
  • 999
  • 5
  • 2