更新特定列中的值并在整个数据库中维护它

时间:2017-11-17 11:21:36

标签: sql oracle

我需要用另一个值替换一个值,并通过oracle数据库中的表来维护它。

例如: 我在表tab_a中有一个名为city的列。在城市专栏中,我可以拥有众多城市价值,其中许多将重复。

因此,如果我在表格"a-> b"的城市列中更改了值tab_a,则无论城市列中的哪个位置,都应将其更改为b。

现在假设我有另一个名为"tab_c"的表,其中包含city列。 因此,如果tab_c表的列的城市由值"a"组成,则它也应更改为"b"

有人可以帮我实现这个。

1 个答案:

答案 0 :(得分:0)

这将是一个很好的关系设计 - 您有一个dedicated table with cities tab_city with a PK and city_name . Other tables use the PK ID`来引用它。

create table tab_a
(id number,
city_id number);

create table tab_b
(id number,
city_id number);

create table tab_city
(id number,
city_name number);

更改城市名称是city_tab的重新更新,因为ID保持不变。

update tab_city
set city_name = 'New York'
where id = 1;
-- 1 record updated, former name  of ID = 1 was "York"

与此相反,您的设计会使用名称标识城市。这是有问题的,因为每次更改都必须更新所有引用。

create table tab_a
(city_name varchar2(100));

create table tab_b
(city_name varchar2(100));

在执行下面的更新时,您会立即看到与propper关系设计的区别。

update tab_a
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated

update tab_b
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated