Anton Putov
Anton Putov

Reputation: 1981

UNION before INNER JOIN

Why when I use UNION before INNER JOIN like this

    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 

I have an eror: could not bound multi-part identifer "some_table3.some_column1"? All data types are compatible.

Upvotes: 7

Views: 45807

Answers (3)

Taryn
Taryn

Reputation: 247630

You are getting an error because that is not valid SQL Syntax. UNION ALL syntax is:

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

You cannot reference the columns from either query like you are trying to do. If you want to reference, then you will want to use something like this:

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 

Upvotes: 28

Phil Sandler
Phil Sandler

Reputation: 28016

I am guessing you are going for something like this?

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 

Upvotes: 2

You're trying to join some_table1 to some_table3 when some_table1 doesn't exist in the second half of the query, only the first.

Upvotes: 2

Related Questions