Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: cascade UNION and JOIN

Tags:

sql

join

union

I have a union opertaion between two tables

SELECT ID_1,
       name_1,
       surname_1,
  FROM T_ONE
 UNION
SELECT ID_2,
       name_2,
       surname_2
  FROM TABLE_2

I want to join the result of this UNION operation with another table or even with all TABLE_1.

How can I handle this new table result of the UNION.

for example after the previous UNION:

RIGHT JOIN TABLE_3
        ON TABLE_3.ID_3 = XXXXXXXXXXXXXXXXXXXX.ID_2

I really do not know what I need to put instead of the XXXXXXXXXXXXXXXX to andle the new table generated by the UNION.

like image 465
Lopoc Avatar asked Sep 13 '09 18:09

Lopoc


People also ask

Can I use UNION and join in SQL?

Both Joins and Unions can be used to combine data from two or more tables. The difference lies in how the data is combined. Joins combine data into new columns. If two tables are joined together, then the data from the first table is shown in one set of column alongside the second table's column in the same row.

What is diff between join and UNION?

There is a major difference between JOIN and UNION in SQL. Using the JOIN clause, we combine the attributes of two given relations and, as a result, form tuples. Whereas we use the UNION clause when we want to combine the results obtained from two queries. They both combine data differently.

Which is faster UNION or join?

Union will be faster, as it simply passes the first SELECT statement, and then parses the second SELECT statement and adds the results to the end of the output table.

What are UNION and join operations performed on a distributed query?

Union and Join are SQL clauses used to perform operations on more than one table in a relational database management system (RDBMS). They produce a result by combining data from two or more tables. But, the way of combining the data from two or more relations differ in both clauses.


2 Answers

Use a derived table like "foo" here, and then JOIN again however you wish:

SELECT
    *
FROM
    TABLE_3
    LEFT JOIN
    (
    SELECT ID_1, name_1, surname_1, FROM T_ONE
    UNION --ALL would be more efficient if results do not overlap, as van's comment said
    SELECT ID_2, name_2, surname_2 FROM TABLE_2
    ) foo  ON TABLE_3.ID_3 = foo.ID_1

PS. Use LEFT joins: less confusing then RIGHT joins.

like image 174
gbn Avatar answered Sep 30 '22 10:09

gbn


You need to provide a join in both SELECT :

SELECT ID_1, name_1, surname_1, FROM T_ONE
RIGHT JOIN TABLE_3 ON TABLE_3.ID_3 = T_ONE.ID_1

UNION

SELECT ID_2, name_2, surname_2 FROM TABLE_2
RIGHT JOIN TABLE_3 ON TABLE_3.ID_3 = TABLE_2.ID_2

Or something like that. Don't forget that a UNION eliminates the duplicates, so if you want duplicates to be included, uyse UNION ALL

like image 22
MaxiWheat Avatar answered Sep 30 '22 12:09

MaxiWheat