1, SQL Server automatically left join automatically converted into inner join question:
The following two statements are left join, but has transformed into a inner join
-
drop
table a,B
-
go
-
-
create
table a(
id
int)
-
-
insert
into a
-
select
1
union all
-
select
2
-
-
create
table b(
id
int,xxx
varchar(
10))
-
-
insert
into b
-
select
1,
'xxx'
union all
-
select
2,
'xx'
-
go
-
-
-
--这个还是left join
-
select *
-
from a
-
left
join b
-
on a.id = b.id
and b.xxx =
'xxx'
-
/*
-
id id xxx
-
1 1 xxx
-
2 NULL NULL
-
*/
-
-
-
select *
--这个就是转化为inner join
-
from a
-
left
join b
-
on a.id = b.id
-
where b.xxx =
'xxx'
-
/*
-
id id xxx
-
1 1 xxx
-
*/
The following diagram is the implementation plan:
2, the following statement, after running a few records will come out of it?
-
select*
-
from
-
(
-
select
1
as
id
-
)a
-
-
left
join
-
(
-
select
1
as
id
-
union all
-
select
1
-
)b
-
on a.id = b.id
-
-
left
join
-
(
-
select
1
as
id
-
union all
-
select
1
-
)c
-
on a.id = c.id
-
The reason thought about this, is because it was discovered recently wrote a report run does not always result, larger numbers, than the logic above statements statements complicated, but the problem is the same.
First, the query results in claim out of detailed data, since the table a correlation table b, although the table a no duplicate records, the list b has duplicate records, resulting in association recording two a record in the table a and table b, the result there are two assemblies, then the result set is then generated and then associated with a table c, c this case, since the table data would be repeated, then the final result set will be four.
Cartesian product looks the same as 2 * 2 = 4, but the fact is that table b and c table have duplicate records, a lot of duplicate data appears after the association is, the problem in time to write SQL statements, we must pay close attention.
If you solve this problem?
Generally separately prior data is repeated to re-table, or group by polymerization and calculated according to the demand, and then associate, so as not to cause too large numbers.