简体   繁体   中英

Update table column primary key based on mapping table

I have two tables.

  1. table contains records with column A (type number, primary key).
  2. table contains records with columns A, B (type number). The second represents mapping table.

What is the problem?

I need to do remapping all records in table 1, specifically column A to column B based on mapping table 2. But the problem is that table 1 contains records which have also values B from table 2 (in column A). That means when I will do remapping table 1 then can appear problem with uniqueness because column A in table 1 is primary key.

I have tried to select count of all records which have to be remapped but I dont know exactly if my query is correct.

Here are those two tables:

select * from temp_1;
select * from temp_2;

Here is the select with count:

SELECT count(*) FROM temp_1 T1
WHERE EXISTS (SELECT 1 FROM temp_2 T2 WHERE T2.a = T1.a
and not exists (select 1 from temp_1 T1b where T2.b = T1b.a));

Sample data:

Table 1:
1, 2, 3, 4, 5, 40, 50

Table 2:
1-11, 2-22, 3-33, 4-40, 5-50

Result Table 1 after remapping:
11, 22, 33, 4, 5, 40, 50 remaining problem values

These bold marked values are the problem values if you understand me.

So, you have table 1 with column A that contains values that may also appear as new values from the re-mapping. The only solution is to use a temporary table into which you deploy the new mapping and, once you are done, copy the new mapping onto table 1.

This is not an answer - posting as one so the query can be formatted.

You may want to check to see if the PK constraint is deferrable. For example, you could run the query below. '......' means your table name, in single quotes (and in ALL CAPS). If the tables aren't yours, query ALL_CONSTRAINTS instead of USER_CONSTRAINTS. If you are lucky, the constraint is deferrable. If not we can think about other solutions. Good luck!

select constraint_name, deferrable, deferred
from   user_constraints
where  constraint_type = 'P'
  and  table_name = '.....'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM