patternsqlMinor
How does LEFT JOIN with WHERE clause works?
Viewed 0 times
leftwithwherejoinworksdoeshowclause
Problem
Given the query below
.
.
What baffles me is the process that is happening behind.
Does the system JOINs first both tableA and tableB before they select only the row from the WHERE clause?
If yes, then what about this query
Does this query select first using the WHERE clause before it JOINs the other table?
Sorry I can't find the answer on the web. I wanted to lessen the MySQL resource bandwidth. Does the second query is the best for this situation?
SELECT * FROM tableA
LEFT JOIN tableB ON tableB.id = tableA.id
WHERE tableA.name = 'e'.
tableA tableB
----------- -----------
id name id school
----------- -----------
1 a 1 AA
2 b 2 BB
3 c 3 CC
4 d 4 DD
5 e 5 EE.
What baffles me is the process that is happening behind.
Does the system JOINs first both tableA and tableB before they select only the row from the WHERE clause?
If yes, then what about this query
SELECT * FROM
(
SELECT * FROM tableA
WHERE name = 'e'
) A LEFT JOIN tableB ON tableB.id = A.idDoes this query select first using the WHERE clause before it JOINs the other table?
Sorry I can't find the answer on the web. I wanted to lessen the MySQL resource bandwidth. Does the second query is the best for this situation?
Solution
The query optimizer will decide and it is pretty smart.
There are many cases where doing the join first is more efficient. If name is indexed and 'e' is somewhat unique then do that first is more efficient.
This is different
That changes the left join into an inner join but since there is a match in your data you would get the same results.
SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id = tableA.id
WHERE tableA.name = 'e'There are many cases where doing the join first is more efficient. If name is indexed and 'e' is somewhat unique then do that first is more efficient.
This is different
SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id = tableA.id
WHERE tableB.school = 'EE'That changes the left join into an inner join but since there is a match in your data you would get the same results.
Code Snippets
SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id = tableA.id
WHERE tableA.name = 'e'SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id = tableA.id
WHERE tableB.school = 'EE'Context
StackExchange Database Administrators Q#165642, answer score: 7
Revisions (0)
No revisions yet.