2014-02-10 31 views
2

以下查询两个匿名表运行:加入相互

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'. 

为什么是错误?有没有可能以某种方式加入这些表格?

回答

2

给的名字给你的表使用As <temp_table_name>,你需要指定两个表都加入ON。由于没有列加入ON我使用同义反复(总是导致True)假设你希望得到的结果是:你好世界两列

这里是重新排列查询:

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

您需要给别名赋予别名。下面的代码工作

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

错误是由于缺少ON关键字引起的。 ON子句的工作方式与WHERE子句相同,并且是您添加加入过滤器的位置。

它没有直接关系缺乏别名上的表和列,但如果你不命名列和表的ON子句不能知道你想要的结果什么和如何你想加入

+0

表,但你可以在postgres中做到这一点:'select * from foo join bar',其中foo和bar是表格。 – reox

+1

我缺乏关于postgres的知识,但是没有过滤器的连接表的独特方式是交叉连接(表行之间的笛卡尔积)。这似乎是它。 – jean

+0

啊我明白了!所以命名不同 – reox