外连接sql的一个问题
当在内连接查询中加入条件时,无论是将它加入到join子句,还是加入到where子句,其效果是完全一样的,但对于外连接情况就不同了。当把条件加入到 join子句时,会返回外连接表的全部行,然后使用指定的条件返回第二个表的行。如果将条件放到where子句中,将会首先进行连接操作,然后使用where子句对连接后的行进行筛选。例如:
(1)
select u.id, u.p_plan_id, u.unit_name, p.id, p.plan_name
from t_baidu_p_units u
left outer join t_baidu_p_plans p on u.p_plan_id = p.id
and p.id = 3176
where 1 = 1
order by u.p_plan_id desc
它会返回t_baidu_p_units表中所有行,t_baidu_p_plans表中符合join条件的字段不为null
(2)
select u.id, u.p_plan_id, u.unit_name, p.id, p.plan_name
from t_baidu_p_units u
left outer join t_baidu_p_plans p on u.p_plan_id = p.id
and p.id = 3176
where p.id is null
order by u.p_plan_id desc
查询的结果集中没有符合join条件的数据
(3)
select u.id, u.p_plan_id, u.unit_name, p.id, p.plan_name
from t_baidu_p_units u
left outer join t_baidu_p_plans p on u.p_plan_id = p.id
and p.id = 3176
where p.id is not null
order by u.p_plan_id desc
结果集中只包含join条件的数据
分析一下:
(1)where1=1对其进行过滤时,由于都符合此条件,因此没有改变结果集
(2)根据where p.id is null对于join后的结果集进行筛选,凡是p.id不为null的都要过滤掉,因此自然没有p.id=3176的结果
(
相关文档:
比如在Northwind数据库中
有一个查询为
SELECT c.CustomerId, CompanyName
from Customers c
WHERE EXISTS(
SELECT OrderID from Orders o
WHERE o.CustomerID = cu.CustomerID)
这里面的EXISTS是如何运作呢?子查询返回的是OrderId字段,可是外面的查询要找的是CustomerID和CompanyName字段,这两个字段肯 ......
Aaron Bertrand
Adam Machanic
All Things SQL Server
Allen Kinsel - SQL DBA
Allen White
Amit Bansal writes...
Andrew Fryer's Blog
Andrew Kelly
Andy Leonard
Anything and Everything IT
Arcane Code
Arnie Rowland: Ramblings of a Harried Technogeek
B.I. for the SQL Guy
Bart Duncan's SQL Weblog ......
declare @ID varchar(10)
set @ID=9 --根节点
declare @i int --级数
declare @t table(ID varchar(10),ParentID varchar(10),Level int)
set @i = 1
insert into @t select @ID,0,0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作
insert into @t select ID,ParentID,@i from t_ ......
2005不论是性能还是安全性都是SQL SERVER2000有所增强,现有不少企业在使用2005,或是有的用户是2000与2005同时使用,那么这中间就涉及到双数据的转换问题:
今天我们就来看一下相关的实现方法:
本人的实现环境介绍:
方法一: 使用分离与附加 该方法适合于将SQL Server 2000中的数据转换到SQL Server2 ......