6
Considering the two forms of union of tables through a join
(anyone):
SELECT Tabela.A, Tabela.B, Tabela2.C
FROM Tabela
LEFT JOIN Tabela2 ON Tabela.Id = Tabela2.TabelaId
And a union using from
SELECT Tabela.A, Tabela.B, Tabela2.C
FROM Tabela, Tabela2
WHERE Tabela.Id = Tabela2.TabelaId
Since the data to be returned are the same.
In one of the querys that rotate in my application, when used union through the from
instead of a join
the difference in performance is very high.
- Union with from: 8s
- Union with Join: 0.2s
What is the difference between these unions? When using one instead of the other?
I think you should always use JOIN when you need information from two or more tables that relate, JOIN should be optimized precisely for this.
– Kayo Bruno
Behold that answer. In your example, the first is a LEFT JOIN the second is a CROSS JOIN
– Pagotti
@Pagotti a union with FROM is equivalent to a Cross Join ?
– LP. Gonçalves
@LP.Gonçalves It’s called cross implicit Join
– Pagotti
@Pagotti is not a
CROSS JOIN
, for that he could not have theWHERE
, due toWHERE Tabela.Id = Tabela2.TabelaId
he becomes aINNER JOIN
– Leandro Godoy Rosa
@Leandrogodoyrosa The joins have to do with the clase
FROM
. The clauseWHERE
has another function in theSQL
. The final result of the query is the same, but the way it behaves within the optimizer is different. Look for "Relational Algebra" to better understand these differences. There this interesting online tool that shows how SQL works internally.– Pagotti
@Pagotti please refer to the Wikipédia page you linked on the
INNER JOIN
implicit, you will see that as much as it is technically the same as making aCROSS JOIN
, due to the filter by the clauseWHERE
the result is the same of aINNER JOIN
, and in modern databases what will be done is aINNER JOIN
, test see the SQL Server execution plan for example, it may be that in the past it had difference, nowadays it has practically no– Leandro Godoy Rosa