如何创建合并两个表的视图?
我有两个具有完全相同结构的表。两个表可以使用不同的主键(自动递增整数)存储相同的数据。因此,有第三个表列出了哪两个主键列出了相同的数据。但是,也存在其他行中不存在的行。因此,简单的联接不起作用,因为您将有两行具有相同的主键但数据不同。因此,是否有一种方法可以将主键重新分配给视图中未使用的值?
表1
ID name 1 Adam 2 Mark 3 David 4 Jeremy
表2
ID name 1 Jessica 2 Jeremy 3 David 4 Mark
表3
T1ID T2ID 2 4 3 3 4 2
我正在寻找如下所示的结果表:
结果
ID name 1 Adam 2 Mark 3 David 4 Jeremy 5 Jessica
问题的真正核心是我如何将临时假ID 5 分配给杰西卡,而不仅仅是一些随机数。我想要的 id 规则是,如果该行存在于第一个表中,则使用它自己的 id。否则,使用插入语句生成的下一个 id(该列处于自动增量状态)。
I have two tables which have the exact same structure. Both tables can store the same data with different primary keys (autoincremented integers). Therefore, there is a third table which lists which two primary keys list the same data. However, there also exist rows which don't exist in the other. Therefore, a simple join won't work since you will have two rows with the same primary key but different data. Therefore, is there a way of reassigning primary keys to unused values in the view?
Table1
ID name 1 Adam 2 Mark 3 David 4 Jeremy
Table2
ID name 1 Jessica 2 Jeremy 3 David 4 Mark
Table3
T1ID T2ID 2 4 3 3 4 2
I am looking for a result table like the following:
Result
ID name 1 Adam 2 Mark 3 David 4 Jeremy 5 Jessica
The real heart of the question is how i can assign the temporary fake id of 5 to Jessica and not just some random number. The rule I want for the ids is that if the row exists in the first table, then use its own id. Otherwise, use the next id that an insert statement would have generated (the column is on autoincrement).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑问题的答案
MAX(id) 用于“预测”如果将第二个表中的数据合并到第一个表中将会出现的下一个身份。如果 Table3.T2ID 存在,则意味着它已包含在 table1 中。
使用下面的测试数据
回答下面的原始问题
那么第三个表是您想要构建的表(视图而不是表)?
数据将包含每个记录的唯一
newid
值,无论是来自第一个表还是第二个表。将pk_id
更改为您的主键列名称。Answer to edited question
The MAX(id) is used to "predict" the next identity that would occur if you merged the data from the 2nd table into the first. If Table3.T2ID exists at all, it means that it is already included in table1.
Using the test data below
Answer to original question below
So the 3rd table is the one you want to build (a view instead of a table)?
The data will contain a unique
newid
value for each record, whether from first or second table. Changepk_id
to your primary key column name.假设您有以下数据,据我了解,阅读您的问题:
T1 有一些数据不在 T2 中,反之亦然。
以下查询将给出所有数据联合
Assuming you have below data, as I understand reading your question:
T1 has some data which is not in T2 and vice versa.
Following query will give all data unioned
如果我理解正确,以下可能会起作用
测试数据
SQL 语句
If I understand you correct, following might work
Test data
SQL Statement