Why these two statements have different results?
mysql> select a.id,a.parent from qa a left join qa b on a.parent=b.parent where b.id=7;
+----+--------+
| id | parent |
+----+--------+
| 7 | 1 |
| 8 | 1 |
| 9 | 1 |
+----+--------+
3 rows in set (0.00 sec)
mysql> select a.id,a.parent from qa a left join qa b on a.parent=b.parent and b.id=7;
+----+--------+
| id | parent |
+----+--------+
| 1 | NULL |
| 2 | NULL |
| 3 | NULL |
| 4 | NULL |
| 5 | NULL |
| 6 | NULL |
| 7 | 1 |
| 8 | 1 |
| 9 | 1 |
+----+--------+
I read the开发者_JAVA技巧m exactly the same!
The first statement will create the join, and then filter the result using WHERE b.id=7.
So only rows from a where a.parent=b.parent and that join result has b.id=7.
The second statement will create the left join with the b.id=7, thus including all rows from qa a, and then only values from qa b where b.id=7.
So all rows from a where a.parent=b.parent, but show values from b only where b.id=7
you first query is limiting the right hand side of your result by automatically eliminating the NULLs
that a LEFT JOIN
can/will return. The statementds would return the same results if you were using an INNER JOIN
.
First has a condition (where
) on the select statement, second applies b.id condition on the join.
From the docs:
If there is no matching row for the right table in the ON or USING part in a LEFT JOIN, a row with all columns set to NULL is used for the right table.
精彩评论