Here is my table structure: SQL Fiddle
CREATE TABLE mytable (
id int,
related int
);
INSERT into mytable VALUES(1, NULL);
INSERT into mytable VALUES
In first case, we need to match values 1, 2, 3 with NULL
, 1 and 1. Since it is left join
, NULL
will stay with no match and 1's will be matched with 1 from other table, thus 3 records.
In the second case, we have values 1, 2, 3. 2 and 3 have no match and will result in two rows, but 1 has 2 matches and will result in 2 additional rows, which is 4 rows.
Generally, having:
... LeftTable [LT] left join RightTable [RT] on [LT].[joinCol] = [RT].pjoinCol] ...
will work like this:
take all values from LT.joinCol
, try to match with values in RT.joinCol
. If some value has n
matches in RT.joinCol
, then it will result in n
rows. If the row has no match, it will still result in one, un-matched record.
In your 1st case, 2 values have 1 match => 1 + 1 = 2
records. One value has no match => 1 record, 2 + 1 = 3
.
In your 2nd case, 2 values have no match => thus 2 records, one value has 2 matches => 2 records, 2 + 2 = 4
:)