'Creating column based on other table's column in postgreSQL
I have two tables which is 'table1' and 'table2' , table1 looks like this
| elements |
|---|
| youtube |
| youtube |
and other table table2 looks like this
| id | e |
|---|---|
| 1 | youtube |
| 2 | |
| 3 |
i want to make column "e_id" in table1 based on element's "id" in table2
so the result may look like this
| elements | e_id |
|---|---|
| 2 | |
| 3 | |
| youtube | 1 |
| 2 | |
| youtube | 1 |
the e_id should be dynamic ( like if element is found in the table2, it will assign its id in e_id column )
is there a optimized way to do this in postgreSQL?
Solution 1:[1]
Not sure about optimized way but you need to alter your table1 first then you do an update on it. cheers!
ALTER TABLE table1
ADD COLUMN e_id int;
UPDATE table1
SET table1.e_id = table2.id
FROM table2
WHERE table1.elements = table2.e
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eNca |
