我有兩個資料表,我可以使用在兩個表中的 ID 上鏈接的左連接來連接它們。如果課程和人員相同,我需要將 RegNumber 填充為與已經存在 1 行的 RegNumber 相同的:
當前情況:如果我使用左連接連接表 1 和表 2。
表格1
ID | Course| Person
67705 | A | 1
68521 | A | 1
85742 | A | 1
89625 | A | 1
67857 | B | 2
86694 | B | 2
88075 | B | 2
88710 | C | 3
47924 | C | 3
66981 | C | 3
12311 | B | 1
12312 | B | 1
12313 | B | 1
表 2
ID | RegNumber
67705 | N712316
NULL | NULL
NULL | NULL
NULL | NULL
67857 | N712338
NULL | NULL
NULL | NULL
NULL | NULL
47924 | M481035
NULL | NULL
12311 | N645525
NULL | NULL
NULL | NULL
我需要表 2 看起來像這樣:
ID | RegNumber
67705 | N712316
68521 | N712316
85742 | N712316
89625 | N712316
67857 | N712338
86694 | N712338
88075 | N712338
88710 | N712338
47924 | M481035
66981 | M481035
12311 | N645525
12312 | N645525
12313 | N645525
也就是說,我需要在表 2 中插入新行
有人可以幫我嗎?這完全超出了我的能力!
uj5u.com熱心網友回復:
insert into table2 (ID,RegNumber)
select t1.ID,reg.regNumber
from table1 t1
cross join (select top 1 regNumber from table2 r2 join table1 r1
on r1.Id = r2.Id
and r1.Course = t1.Course
and r1.Person = t1.person
order by id) reg
where not exists (select 1 from table2 t2 where t1.ID = t2.ID)
您可以通過首先將資料加載到臨時表來稍微提高性能:
select t1.ID , Course,Person,regNumber
into #LoadedData
from table1 t1
join table2 t2 on t1.Id = t2.ID
insert into table2 (ID,RegNumber)
select t1.ID,reg.regNumber
from table1 t1
cross join (select top 1 regNumber from #LoadedData l
where l.Course = t1.Course
and l.Person = t1.person
order by id) reg
where not exists (select 1 from #LoadedData l where t1.ID = l.ID)
在任何一種情況下,在 (ID, Course, Person) 上都有一個索引將有助于提高性能
uj5u.com熱心網友回復:
假設:
- 您缺少表 2 中從表 1 中的其他記錄繼承資料的專案。
- 使兩個不同的 ID 共享相同的 Regnumber 的原因是具有共同的課程和人員編號。
您確實需要將表 1 連接到自身以創建將 ID 67705 與 ID 68521 相關聯的映射,然后您可以加入表 2 以獲取 Regnumber。
嘗試這個:
Insert into table2 (ID,RegNumber)
Select right1.ID, left2.RegNumber
From (
(table2 left2 INNER JOIN
table1 left1 On (left1.ID=left2.ID)
INNER JOIN table1 right1 On (left1.Course=right1.Course AND left1.Person=right1.Person)
) LEFT OUTER JOIN table2 right2 On (right1.ID=right2.ID)
WHERE right2.ID Is Null
第 4 個表連接(別名 right2)純粹是防御性的,用于處理 table2 中在 table1 中具有相同 Person 和 Course 的兩條記錄。
uj5u.com熱心網友回復:
我自己解決了這個問題。我連接了 person 和 course 列,然后使用新的連接欄位加入了它們
insert into table 2 (ID,RegNumber)
select X1.ID,X2.Regnumber
from (select concat(course,person) as X,ID from table1) X1
join (select concat(t1.course,t1.person) as X, t2.RegNumber
from table1 t1
join table2 t2 on t1.ID = t2.ID) X2
on X1.X = X2.X
where X1.ID not in (select ID from table2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349937.html
標籤:sql sql-server sql 插入
