目前,我有一個如T1所示的表,我想將其拆分為單獨的Person表,如T2和一個PersonClientLink表,如T3。每個關系在 T1 中都存盤為它自己的唯一 ID。這使得同一個人及其客戶的副本變得困難。我需要將 T1 中的人員分組到一個 ID 中,基本上將其轉換為 T2 并為他們與 T3 中的每個關系創建鏈接。T3目前存在但為空,我想先根據T1中的資料填充T3,然后將T1變成T2。任何意見,將不勝感激 :)
T1 - 當前混亂
| ID | 客戶編號 | 姓名 |
|---|---|---|
| 1個 | 5個 | 鮑勃 |
| 2個 | 6個 | 鮑勃 |
| 3個 | 7 | 格雷格 |
| 4個 | 8個 | 格雷格 |
T2 - 人
| ID | 姓名 |
|---|---|
| 1個 | 鮑勃 |
| 2個 | 格雷格 |
T3 - PersonClientLink
| ID | 人物編號 | 客戶編號 |
|---|---|---|
| 1個 | 1個 | 5個 |
| 2個 | 1個 | 6個 |
| 3個 | 2個 | 7 |
| 4個 | 2個 | 8個 |
老實說,我一無所知,不知道從哪里開始......
uj5u.com熱心網友回復:
我將創建 T2 和 T3 表并從 T1 填充它們。之后我會放棄 T1。下面是用postgresql做的,不過應該是一樣的。postgresql 中的序列列與 sqlserver 中的標識列相同。
create table t2 (id serial primary key,
name varchar(32) not null);
create table t3 (id serial primary key,
person_id integer not null,
client_id integer not null);
創建一個從 t3.person_id 到 t2.id 的外鍵
填充 t2 和 t3:
insert into t2 (name) (select distinct name from t1);
insert into t3 (person_id,client_id) (
select t2.id,t1.client_id from t1,t2 where t2.name = t1.name);
如果 sqlserver 需要,將表的連接轉換為 ANSI 樣式。
初始資料(與您的相同)和結果:
select * from t1;
id | client_id | name
---- ----------- ------
1 | 5 | bob
2 | 6 | bob
3 | 7 | greg
4 | 6 | greg
(4 rows)
select * from t2;
id | name
---- ------
1 | bob
2 | greg
(2 rows)
select * from t3;
id | person_id | client_id
---- ----------- -----------
1 | 1 | 6
2 | 1 | 5
3 | 2 | 6
4 | 2 | 7
(4 rows)
我希望這有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/534688.html
上一篇:與字串映射相比,使用JsonDocumentDOM映射存盤不穩定的json資料有什么缺點嗎?
下一篇:SQL2008中的回圈
