Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
Anton Putov Avatar asked Sep 19 '12 17:09

Anton Putov


1 Answers

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 
like image 187
Taryn Avatar answered Oct 21 '22 15:10

Taryn