我想比较3个SQL Server表

问题描述:

我创建了三个表Table1,Table2和Table3。我想比较3个SQL Server表

  • 表1我有3列CodeName & Cityid
  • 表2我有2列Code & Name
  • 表3我有2列Code & Cityid

在这些第一,我必须比较Table1.NameTable2.Name

如果该条件满足,则取Table2.Code并将其与Table3.Code进行比较,然后取Table3.Cityid并将其与Table1.Cityid进行比较。

如果满足所有条件,则将Table2.Code插入Table1.Code

请任何人帮助我写下查询我是新的SQL。

在此先感谢。

请参阅输入采样数据

table1的 |名称|码| cityid | | ------------- | --------- | ------ | | Ersan | NULL | 1 | | Plovdiv | NULL | 3 |

table2 | name | code | | ------------- | --------- | | Ersan | 401065 | | Ersan | 401065 | |普罗夫迪夫| 143967 | |普罗夫迪夫| 143967 | |普罗夫迪夫| 143967 |

table3 | cityid | code | | --------- | --------- | | 1 | 401065 | | 3 | 143967 |

,输出会是这样的:

table1的 |名称|码| cityid | | ------------- | --------- | ------ | | Ersan | 401065 | 1 | |普罗夫迪夫| 143967 | 3 |像下面

table__1

+0

没有任何示例数据,它真的很难遵循你实际上想要实现的。 –

+0

对不起,刚才我添加了一个样本数据图像。请参考.Thankyou –

+0

将样本数据添加为图像并不是很有帮助。请尝试以文本格式添加示例数据,因为使用这些数据更容易。 –

看看我创建的样本数据将

code name city 
0001 a  p 
002  b  c1 
003  c  c2 
004  d  c4 
005  e  c5 
006  f  c6 
007  g  c7 
008  h  c8 
009  i  c9 

table__2将

code name city 
    0001 a  p 
    002  b  c1 
    003  c  c2 
    004  d  c4 
    005  e  c5 
    006  f  c6 
    007 wrongname c7 
    wrongcode h  c8 
    009  i wrongcity 

现在查询插入记录将

insert into table__3 
select table__1.code,table__1.name,table__1.city 
from table__2 inner join table__1 
on table__2.name=table__1.name and table__2.code=table__1.code and table__2.city=table__1.city 

如果有任何问题评论如下... 最好的运气...

+0

谢谢你,但它不适合我。请参阅我的文章中的示例数据。我需要在table1中插入代码,其中table1.name = table2.name。如果满足这个条件取table2.code并在table.code中比较。如果第二个条件也满足,则取table3.cityid并将其与table1.cityId进行比较,然后在table1中插入table2.code。 –

+0

以文本格式添加示例数据... –

+0

并添加预期输出以及 –