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
.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With