【发布时间】:2021-07-16 12:52:24
【问题描述】:
我的数据库(sql 服务器)中有 3 个表。第一个表是我的主表,我正在尝试将其他两个表中的新记录更新/插入到我的主表中
基于 3 个标准。
-
我想维护主表 tbl1 中的所有记录。
-
如果我们在 2 个以上的表(即 tbl2_2020 和 tbl3_2019)中遇到相同 id1、id2、id3、id4 的重复记录,那么我想从最近的记录中获取记录(最近的记录是根据年份选择的在 tbl 名称中)& 最终表中不应有重复记录。
-
应该选择 tbl1 中不存在但在 tbl2 或 tbl3 中的唯一记录
-
在最后的 tbl 中有一个单独的列来描述记录的来源
---my attempt so far (didnt work though :-) )
select COALESCE(t1.id1, t2.id1, t3.id1) as id1,
COALESCE(t1.id2, t2.id2, t3.id2) as id2,
.....so on for all the fields
from tbl1_2021 t1 full join tbl2_2020 t2 ON
t1.id1= t2.id and t1.id2=t2.id2 and t1.id3=t2.id3 and t1.id4=t2.id4
full join
tbl3_2019 t3 ON
t2.id1= t3.id1 and t2.id2=t3.id2 and t2.id3=t3.id3 and t2.id4=t3.id4
tb1_2021:(主要tbl)
| id1 | id2 | id3 | id4 | name | age | website | nation | email | address |
| 1 | 11 | 111 | 1111| raj | 20 | .com | india | | india addr |
| 2 | 22 | 222 | 2222| roger| 21 | .usa | usa |x@x.com| usa |
tbl2_2020:
| id1 | id2 | id3 | id4 | website | name | age | nation | email | zipcode | parentname | device |
| 1 | 11 | 111 | 1111| .com | raj | 20 | india | | | | |
| 3 | 33 | 333 | 3333| .ca | amy | 24 | uk | amy | zip333 | sage | ipad |
tbl3_2019:
| id1 | id2 | id3 | id4 | name | age | website | nation | email | address |
| 3 | 33 | 333 | 3333| | | | | | |
| 2 | 22 | 222 | 2222| roger| 21 | .usa | usa |x@x.com| |
| 4 | 44 | 444 | 4444| nick| 28 | .irl | uk |n@n.com| nickadr|
最终表(输出)
| id1 | id2 | id3 | id4 | name | age | website | nation | email | address | source
| 1 | 11 | 111 | 1111| raj | 20 | .com | india | |india addr| tbl_2021
| 2 | 22 | 222 | 2222| roger| 21 | .usa | usa |x@x.com| usa | tbl_2021
| 3 | 33 | 333 | 3333| amy | 24 | .ca | uk | | | tbl_2020
| 4 | 44 | 444 | 4444| nick | 28 | .irl | uk |n@n.com| nickaddr | tbl_2019
【问题讨论】:
-
如果你想要主表中的记录,那么第 3 行和第 4 行是从哪里来的?
-
如果您每年都有不同的表,那么您就有设计缺陷。希望您提出问题的原因是解决此问题?如果没有,应该是。
-
然而,你所追求的是
FULL OUTER JOIN。或者,您可以在WHERE子句中使用UNION ALL和NOT EXISTS。 -
嗨@GordonLinoff,第三和第四条记录来自我在问题中提到的第三条标准。不存在于 tbl1 但存在于 tbl2 或 3 中的唯一记录有资格被挑选。
-
您好@Larnu,感谢您的反馈!我不否认,不幸的是,我必须仔细研究这些不同的数据块,直到有一个系统到位。
标签: sql sql-server join