Fulfilling join requests before or after UNION

Let's say we have a query that essentially uses a join to combine 2 sets of records into 1. Now I need to duplicate the records, usually using a join. I believe option 1, in my opinion, is the best option for improving performance, but I wondered what SQL Query experts thought.

Basically, I know that the answer is "1". But, I also wonder if I could be wrong - is there a side to this I might miss?

(SQL Server) Here are my options.

pseudo code

Original request:

Select Name, Category from t1
Union
Select Name, Category from t2

Option 1)

Select Name, Category from t1
Inner Join (here)
Union
Select Name, Category from t2
Same inner Join (here)

Option 2)

Select * from (
Select Name, Category from t1
Union
Select Name, Category from t2
) t
(Inner Join Here)
+3
source share
4 answers
SELECT  Name, Category
FROM    t1
JOIN    t_right
ON      right_category = category
UNION
SELECT  Name, Category
FROM    t2
JOIN    t_right
ON      right_category = category

SELECT  *
FROM    (
        SELECT  Name, Category
        FROM    t1
        UNION
        SELECT  Name, Category
        FROM    t2
        ) t
JOIN    t_right
ON      right_category = category

: , , :

t1

Name   Category
---    ---
Apple  1


t2

Name   Category
---    ---
Apple  1

t_right

Category
---
1
1

Apple, 1 , .

, , , :

  • .

  • , .

, , t1 t2, , .

( sargable ) SQL Server , :

SELECT  Name, Category
FROM    t_right
CROSS APPLY
        (
        SELECT  Name, Category
        FROM    t1
        WHERE   t1.Category = t_right.category
        UNION
        SELECT  Name, Category
        FROM    t2
        WHERE   t2.Category = t_right.category
        ) t
+5

, . , , ( ), .

, ... : , / . .

+1

2, - ( ) - .

1 t1, "", t2, , "", .

2 t2, t2, ( , UNION ALL) "".

, 1 "", 2 . , .

0

, "( " ) .

0

Source: https://habr.com/ru/post/1721297/


All Articles