INNER JOIN之前的UNION

时间:2012-09-19 17:07:47

标签: sql union inner-join

为什么我在INNER JOIN之前使用UNION就像这样

    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 

我有一个错误:无法绑定多部分标识符“some_table3.some_column1”? 所有数据类型都是兼容的。

3 个答案:

答案 0 :(得分:18)

您收到错误,因为它不是有效的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 

答案 1 :(得分:2)

当您在查询的后半部分中不存在some_table1时,您尝试将some_table3加入some_table1,只有第一个。{/ p>

答案 2 :(得分: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