2012-09-19 161 views
5

爲什麼當我INNER之前使用UNION JOIN這樣UNION前INNER JOIN

select some_table1.some_column1, 
      some_table1.some_column2 
    FROM some_table1 
    UNION ALL 
    select some_table2.some_column1, 
      some_table2.some_column2 
    FROM some_table2 
    INNER JOIN some_table3 
    ON some_table3.some_column1 = some_table1.some_column1 

我有一個eror:無法綁定多個部分組成的識別碼 「some_table3.some_column1」? 所有數據類型都是兼容的。

回答

14

您正在收到錯誤,因爲這不是有效的SQL語法。 UNION ALL語法是:

SELECT <column1> 
FROM <table1> 
UNION ALL 
SELECT <column1> 
FROM <table2> 

像你正在嘗試做你不能從任何查詢引用列。如果你想參考,那麼你會想要使用這樣的事情:

select * 
from 
(
    select some_table1.some_column1, some_table1.some_column2 
    FROM some_table1 
    UNION ALL 
    select some_table2.some_column1, some_table2.some_column2 
    FROM some_table2 
) t1 
INNER JOIN some_table3 
ON some_table3.some_column1 = t1.some_column1 
2

你試圖加入some_table1some_table3some_table1不存在於查詢的後半部分時,只有第一個。

2

我猜你是想要這樣的事情?

SELECT 
(
     select some_table1.some_column1, 
       some_table2.some_column2 
     FROM some_table1 
     UNION ALL 
     select some_table2.some_column1, 
       some_table2.some_column2 
     FROM some_table2 
) sub 
     INNER JOIN some_table3 
     ON some_table3.some_column1 = sub.some_column1 
+0

是的,它看起來像我想要的。據我瞭解,我必須在使用INNER JOIN之前對結果進行分組? –