Using two LEFT JOIN
s i.e.
SELECT <some columns>
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON <condition1>
LEFT JOIN Table2 AS t3 ON <condition2>
is this same as using AND
in single LEFT JOIN
? i.e.
SELECT <some columns>
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON <condition1>
AND <condition2>
Both are same or different(in general)?
-
It depends on your requirement and ON condition. If you put t1.col1=t2.col1 with Table2 and t1.col1.t3.col1 It would be same.user98113– user981132016年06月23日 06:19:34 +00:00Commented Jun 23, 2016 at 6:19
-
2The second query would be closer to the first one in terms of results if it used OR instead of AND, but it would still be a different query in general.Andriy M– Andriy M2016年06月23日 06:47:37 +00:00Commented Jun 23, 2016 at 6:47
-
Try using Explain plan to see the difference :)Arnab Datta– Arnab Datta2016年06月23日 09:08:29 +00:00Commented Jun 23, 2016 at 9:08
-
@RajeshRanjan no they wouldn't be equivalent, even in that case.ypercubeᵀᴹ– ypercubeᵀᴹ2016年06月23日 10:23:41 +00:00Commented Jun 23, 2016 at 10:23
1 Answer 1
They are different. In the first option you get 2 times Table2
into your query. Once as t2
and once as t3
. Both have a different content and you must put them somehow back together. To me this is more an OR instead of an AND. In the second option you get only the Table2
rows that meet both criteria.
Suppose you have Table2
with the following content:
| Color | Size |
|-------|------|
| Red | S |
| Blue | S |
| Blue | XS |
Suppose you want to have the rows that are Blue
and S
. In your first option you get all rows (t2
for example with all Blue
and t3
with all S
) and in your second option you only get row 2.
-
4Not only that, but since this is about outer-joining the table twice, you will also get a mini-Cartesian product with the first query. I mean, a
Table1
row wants colour blue and size S. So, the first join gives it twoTable2
matches, thus duplicating theTable1
row, and the second join gives two matches for each of the copies, thus resulting in four rows in total.Andriy M– Andriy M2016年06月23日 06:25:35 +00:00Commented Jun 23, 2016 at 6:25