Sql server 如何加入表格

Sql server 如何加入表格,sql-server,Sql Server,这里我有两个表,我需要加入表,因为我是一个初学者,请帮助我解决 Table1 Table2 ins1 ins2 ins3 Insc0 1 2 0 1 3 4 0 2 5 6 0 3 4 5 下面的代码正确吗

这里我有两个表,我需要加入表,因为我是一个初学者,请帮助我解决

Table1                   Table2
ins1 ins2 ins3           Insc0
 1     2    0              1
 3     4    0              2
 5     6    0              3
                           4
                           5
下面的代码正确吗

select t2.insco from table1 t1
join table2 t2 on t1.ins1=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins2=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins3=t2.insco

正如我提到的,您需要对数据进行标准化。但是,由于数据的简单性,这是非常过分简化的,应该会让您走上正确的道路:

CREATE TABLE dbo.YourTable1 (RowID int--,
                             --Other columns, but no ins1, 2, etc columns
                             );
INSERT INTO dbo.YourTable1 (RowID--,
                            --Other columns
                           )
VALUES(1),(2),(3);--Obviouslu, again you would have other columns, but not an ins columns

CREATE TABLE dbo.YourTable2 (Insc0 int);
INSERT INTO dbo.YourTable2 (Insc0)
VALUES(1),(2),(3),(4),(5);

CREATE TABLE dbo.LinkTable (RowID int,
                            Ins int);
INSERT INTO dbo.LinkTable (RowID,
                           Ins)
VALUES(1,1),(1,2),
      (2,3),(2,4),
      (3,5),(3,6);

GO

SELECT *
FROM dbo.YourTable1 YT1
     JOIN dbo.LinkTable LT ON YT1.RowID = LT.RowID
     JOIN dbo.YourTable2 YT2 ON LT.Ins = YT2.Insc0;

GO

--Clean up

DROP TABLE dbo.LinkTable;
DROP TABLE dbo.YourTable2;
DROP TABLE dbo.YourTable1;

不,这不是正确的方法。主要原因是你的数据没有正常化;你真的应该修复这个设计。这是你现在能做的事吗,在太迟之前?如果没有,您将需要规范化查询中的数据,以获得“最佳”方式。大量的
UNION
查询将是性能最低的方法之一。谢谢@Larnu。对不起,我是初学者。如何规范我的数据?是的,我知道了。。“我会欢迎你的”VigeSHS,请考虑接受答案作为解决方案和/或投票,如果它解决了问题,以便未来读者知道答案是有益的,如果他们有相同的/类似的问题。谢谢。如果能从这里下来,我会很高兴的。如何改进这一点?