9

I have two SQLite tables. I want to update a column in table1 with a value from table2.

Table 1, table1 (id INTEGER AUTOINCREMENT, status TEXT, name TEXT);:

| id |  status   | name |
|----|-----------|------|
|  1 | pending   | xyz  |
|  2 | completed | abc  |

Table 2, table2 (status TEXT, name TEXT, trans_id INTEGER);:

| trans_id |  status   | name |
|----------|-----------|------|
|        1 | refunded  | cvb  |
|        2 | cancelled | asd  |

I want to update status and name from table2 to table1 where table1.id = table2.trans_id. I have this query:

UPDATE table1 
SET status = (SELECT t2.status FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id) , 
name = (SELECT t2.name FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)
WHERE id IN (SELECT trans_id FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)

It populates table1 wrongly. This is the resultant table1

| id |  status  | name |
|----|----------|------|
|  1 | refunded | cvb  |
|  2 | refunded | cvb  |

My requirement is this:

| id |  status   | name |
|----|-----------|------|
|  1 | refunded  | cvb  |
|  2 | cancelled | asd  |

Whats wrong with my query? How can I achieve it?

jww
  • 97,681
  • 90
  • 411
  • 885
Chirag B
  • 2,106
  • 2
  • 20
  • 35

3 Answers3

11

I am assuming that the t2.trans_id is uniq or primary key in table2. If not then if it return multiple result then the update query will blow up. In that case either you need to apply the more filter using the WHERE or use the TOP 1 if any result will be needed.

UPDATE table1
SET    status = (SELECT t2.status
                 FROM   table2 t2
                 WHERE  t2.trans_id = id),
       NAME = (SELECT t2.NAME
               FROM   table2 t2
               WHERE  t2.trans_id = id)
WHERE  id IN (SELECT trans_id
              FROM   table2 t2
              WHERE  t2.trans_id = id) 
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Mahesh
  • 8,694
  • 2
  • 32
  • 53
  • 1
    So essential part here is that we don't need the table which is updated (table1) in the FROM clause. Otherwise, result would be as in the OP (duplicating records in the updated table). – bam Jan 15 '20 at 00:10
5

The previous answer will be failed if there is the id column in the table2. It would be better that using the full name table1.id

UPDATE table1 
SET status = (SELECT t2.status FROM table2 t2 WHERE t2.trans_id = table1.id) , 
    name = (SELECT t2.name FROM table2 t2 WHERE t2.trans_id = table1.id)
WHERE id IN (SELECT trans_id FROM table2 t2 WHERE t2.trans_id= table1.id);
Benjamin
  • 563
  • 6
  • 5
0

as far as table2.trans_id corresponds to table1.id, (preferable with a foreign key), you may update more efficiently:

update table1
Set status=t2.status, name=t2.name
From (
    Select * from table2
) as t2
where table1.Id=t2.trans_id;

There's a new syntax to update 2 columns at once, by I never used it yet.

alex
  • 651
  • 1
  • 9
  • 11