Skip to content
Advertisement

Recreating relation between two tables

I have a 1:1 relation between data that was not an explicit foreign key in the database. E.g.

Table 1 has a once, b twice and c once

Table 2 also has a once, b twice and c once

I want to create a foreign key from Table 1 to Table 2 when the value is the same:

Expected Table 1 after query

I thought about using JOINs but on t1.value = t2.value but those create the cartesian product, and I end up with

How can I populate the fk field in such a way that different rows with the same value receive have different fk?

Advertisement

Answer

You need to JOIN your tables based on the row number of each value in each table; then you can select the id value from Table2 to set the fk column in Table1. First, add the new column:

Then you can UPDATE Table1 with the appropriate id from Table2:

Resultant Table1:

Demo on SQLFiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement