加入结果集机制

时间:2018-03-23 05:52:19

标签: sql sql-server database

查看一个简单的sql代码:

declare @t1 table (id int);
insert into @t1(id) values(1),(2),(3);
select * from @t1

declare @t2 table (id int);
insert into @t2(id) values(9);
select * from @t2

select * from @t1, @t2; -- q1

select ds1.id from @t1 as ds1, (select id from @t2) as ds2 -- q2

为什么q1q2的结果不同,是不是它们应该相同?

1 个答案:

答案 0 :(得分:1)

declare @t1 table (id int);
insert into @t1(id) values(1),(2),(3);
select * from @t1

declare @t2 table (id int);
insert into @t2(id) values(9);
select * from @t2

select * from @t1, @t2; -- q1
select ds1.id from @t1 as ds1, (select id from @t2) as ds2

在这种情况下,(select id from @t2) as ds2被视为派生表。您没有在查询中获取该列。

试试这个:

select ds1.id,ds2.id 
from @t1 as ds1, 
  (select id from @t2) as ds2 -- q2

<强>输出:

id  id
1   9
2   9
3   9