Sql 如何在没有任何条件的情况下连接两个表
例如,我有两个临时表。其中一个只包含ID,另一个包含真实信息。它们的行号完全相同Sql 如何在没有任何条件的情况下连接两个表,sql,sql-server,join,sql-server-2000,Sql,Sql Server,Join,Sql Server 2000,例如,我有两个临时表。其中一个只包含ID,另一个包含真实信息。它们的行号完全相同 #Table1 ID 14 15 16 #Table2 CarModel Year Ford 1996 Ferrari 2005 Toyota 2010 我如何在没有任何条件的情况下将这两个表合并在一个表中,结果表有3列,无论顺序如何?我需要它来插入实际表的结果 Cars ID CarModel Year 这个表不使用标识。有一种自己的机制来获取用于插入的ID。
#Table1
ID
14
15
16
#Table2
CarModel Year
Ford 1996
Ferrari 2005
Toyota 2010
我如何在没有任何条件的情况下将这两个表合并在一个表中,结果表有3列,无论顺序如何?我需要它来插入实际表的结果
Cars
ID CarModel Year
这个表不使用标识。有一种自己的机制来获取用于插入的ID。
我无法改变它
因此,我需要一个表,如下所示,排序并不重要:
#Table3
ID CarModel Year
14 Ford 1996
15 Ferrari 2005
16 Toyota 2010
或
另外,我知道如何使用CTE和row_编号来完成此任务,但我认为有更简单的方法来完成此任务。这段代码可能会在MS SQL Server 2000中使用,因此我很乐意研究解决方案的其他变体。根据Martin Smith的评论,这里有一个三角形连接,可以在SQL Server 2000中使用:
-- Some test data:
declare @Table1 table (
ID int primary key
)
insert into @Table1 select 14
insert into @Table1 select 15
insert into @Table1 select 16
declare @Table2 table (
CarModel varchar(50) not null,
[Year] smallint not null
)
insert into @Table2 select 'Ford', 1996
insert into @Table2 select 'Ferrari', 2005
insert into @Table2 select 'Toyota', 2010
-- Here's the actual query:
select Table1.ID, Table2.CarModel, Table2.[Year]
from (
select ID, (select count(*) from @Table1 where ID < a.ID) as JoinPredicate
from @Table1 as a
) as Table1
join (
select CarModel, [Year], (select count(*) from @Table2 where CarModel < a.CarModel or (CarModel = a.CarModel and [Year] < a.[Year])) as JoinPredicate
from @Table2 as a
) as Table2 on Table1.JoinPredicate = Table2.JoinPredicate
当然,这假设Table1.ID是唯一的,Table2.CarModel+Table2.Year是唯一的
这里很好地讨论了三角形联接的性能注意事项:行数将是实现这一点的方法。然而,我不得不质疑,如果这两个表实际上不包含相关数据,为什么您会希望在这两个表上进行联接。对于SQL Server 2000,您需要使用标识列或三角形连接或使用游标来模拟它。@Tejs感谢您的回答。我需要将此连接日期插入到real not temp表中。我需要插入的行具有ID,这是从存储过程获得的。但我真的不在乎每一行的具体id是什么。我所需要的是,它们都将来自我的池是的,这不是最好的模式,但它是,我必须与之合作。天哪,你真的不应该这样做!不能保证SQL Server会保留任何顺序。你不能随便选一行,然后说嘿,一个查询就有这个ID!。为什么铸造条件复杂?而不是CarModel
-- Some test data:
declare @Table1 table (
ID int primary key
)
insert into @Table1 select 14
insert into @Table1 select 15
insert into @Table1 select 16
declare @Table2 table (
CarModel varchar(50) not null,
[Year] smallint not null
)
insert into @Table2 select 'Ford', 1996
insert into @Table2 select 'Ferrari', 2005
insert into @Table2 select 'Toyota', 2010
-- Here's the actual query:
select Table1.ID, Table2.CarModel, Table2.[Year]
from (
select ID, (select count(*) from @Table1 where ID < a.ID) as JoinPredicate
from @Table1 as a
) as Table1
join (
select CarModel, [Year], (select count(*) from @Table2 where CarModel < a.CarModel or (CarModel = a.CarModel and [Year] < a.[Year])) as JoinPredicate
from @Table2 as a
) as Table2 on Table1.JoinPredicate = Table2.JoinPredicate