7

为什么当我像这样在 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”?所有数据类型都兼容。

4

3 回答 3

24

您收到错误,因为那不是有效的 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 
于 2012-09-19T17:10:31.407 回答
2

您正在尝试加入some_table1何时some_table3some_table1查询的后半部分不存在,只有前半部分。

于 2012-09-19T17:09:36.650 回答
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 
于 2012-09-19T17:11:27.020 回答