2014-02-10 83 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