tags:

views:

54

answers:

2

hello i have two tables: table_1 and table_2

table_1                       table_2
field_1   field_2             field_3      field_4
1          a                  1             
2          b                  4
3          c                  3
4          d                  2

now i need a query using update so that in table_2 i can have follwing values in field_4:

table_2
field_3    Field_4
1              a
4              d
3              c
2              b

should be obtained by update staement in single query using table_1 such that if field_3 of table_2 has 1 then filed_4 should have value equlas to field_2, field_1 in table_1

+2  A: 

In SQL Server, it would be:

UPDATE table_2
 set field_4 = t1.field_2
 from table_2 t2
  inner join table_1 t1
   on t1.Field1 = t2.Field_3

This assumes that field_1 is a primary keys (has unique values). Anything in table_2 not found in table_1 would not be updated. Duplicate field_3 values in table_2 would be properly set.

Philip Kelley
I didn't try, but in sql server I think it needs to be _UPDATE t2_
KM
It doesn't have to be, unless the table being updated is joined on itself (UPDATE X from X inner join X), in which case it gets a bit too complex to discuss in a comment box.
Philip Kelley
+1, I tried it both ways: _UPDATE table_2_ and _UPDATE t2_ and both work. I generally tend to do _UPDATE alias_ when I use an alias in a joined update.
KM
thanx but i need update ststement without using join plz help as soon aspossible
Didn't realise that we couldn't use joins--but why not? What about subqueries or nested queries? What are the real constraints to this problem?
Philip Kelley
A: 

Yeah, since you aliased the tables, I think he's right. The correct answer would be:

    UPDATE t2
       SET field_4 = t1.field_2
      FROM    table_2 t2
       INNER JOIN
          table_1 t1
       ON t1.Field1 = t2.Field_3
DavidStein
thanx but i need update ststement without using join plz help as soon aspossible