0

I have two tables that are identical in structure. Table1 holds moderated data, table2 holds the rest.

Table 1

+------+--------+---------------+--------+-----------+
| "id" | "name" | "description" | "type" | "country" |
+------+--------+---------------+--------+-----------+
| "1"  | "a"    | "x"           | "1"    | "US"      |
| "2"  | "b"    | "x"           | "1"    | "UK"      |
+------+--------+---------------+--------+-----------+

Table 2

+------+-----------+-----------------+--------+-----------+----------+
| "id" |  "name"   |  "description"  | "type" | "country" | "status" |
+------+-----------+-----------------+--------+-----------+----------+
| "1"  | "Title 1" | "Description 1" | "1"    | "US"      | "0"      |
| "2"  | "Title 2" | "Description 2" | "10"   | "UK"      | "0"      |
+------+-----------+-----------------+--------+-----------+----------+

I run the below sql in order to update table 1 with data from table 2, and it works well. The only problem is, I need to specify the id in both places. If I were to specify it only in one place, where would it go?

UPDATE table1 dest, 
       (SELECT name, 
               description 
        FROM   table2 
        WHERE  id = 1) src 
SET    dest.name = src.name, 
       dest.description = src.description 
WHERE  dest.id = 1; 

The way this thing goes is:

UPDATE table1 SET name AND description =
(
   SELECT name, description from table2
   WHERE id=1 AND country=us and type=10
) WHERE id=idfromselect AND country=countryfromselect AND type=typefromselect

I can't figure out where to put the id and remaining conditions. Can you help?

totymedli
  • 29,531
  • 22
  • 131
  • 165
jmenezes
  • 1,888
  • 6
  • 28
  • 44
  • You can use a join condition see this link it might help http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match – learner Jun 04 '13 at 11:40

2 Answers2

1

Do it as a join, put the id in the join condition and just check the id in the WHERE clause.

Something like this:-

UPDATE table1 dest INNER JOIN table2 src ON dest.id = src=id
SET dest.name = src.name, dest.description = src.description 
WHERE dest.id=1 ;

Any other restrictions can just be added to the WHERE clause

Kickstart
  • 21,403
  • 2
  • 21
  • 33
1

I think you can use an INNER JOIN query to update your table1 basing on data from table2 and put your condition in WHERE clauses

UPDATE table1 a
INNER JOIN table2 b
ON a.id = b.id
SET a.name = b.name,
a.description = b.description
WHERE a.id=1;
Fabio
  • 23,183
  • 12
  • 55
  • 64