加入两个匿名表

时间:2014-02-10 10:09:15

标签: sql sql-server

以下查询运行:

select foo.g from (select 'hello' as g) as foo

并且此查询也会运行:

select bla.x from (select 'world' as x) as bla

但这个没有:

select * from (select foo.g from (select 'hello' as g) as foo) join (select bla.x from (select 'world' as x) as bla)

我收到以下错误消息:

Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'join'.

为什么会出错?是否有可能以某种方式加入这些表?

3 个答案:

答案 0 :(得分:2)

您需要为表格指定别名。以下代码可以使用

select * from (select foo.g from (select 'hello' as g) as foo) T1
join (select bla.x from (select 'world' as x) as bla) T2 on t1.g=t2.x

答案 1 :(得分:2)

使用As <temp_table_name>为您的表提供名称,并且您需要指定两个表正在加入ON。由于没有要加入的列ON我使用重言式(总是会产生True),假设您期望的结果是: hello 世界分两列

以下是重新排列的查询:

select * 
from 
(
    select foo.g 
    from 
    (
        select 'hello' as g
    ) as foo
) As t1
inner join 
(
    select bla.x 
    from (select 'world' as x) as bla
) As t2 ON 1 = 1

答案 2 :(得分:1)

该错误是由于缺少ON关键字。 ON子句的作用类似于WHERE子句,是您添加加入过滤器的位置。

它与表和列上缺少 names 别名没有直接关系,但如果没有为列和表命名{{1} }子句无法知道您想要的结果以及如何在

上连接表