我看SQL SERVER2008编程入门经典这本书【作者:】时产生了这个疑问,刚开始的时候还没注意,仔细一看书上的例子,
SELECT Name
FROM Production.product
WHERE ProductID=365ProductID是product表的主键。类似这样的例子很多。还有有个我没弄懂的例子,书上在讲述处理分层数据的时候 有段这样的代码
USE AdventureWorks2008SELECT
Thereport.EmployeeID,
Thereport.JobTitle,
Thereport.LastName,
Thereport.FirstName,
From
HumanResources.Emplyee2 as TheBoss
JOIN
HumanResources.Emplyee2 as Thereport
ON
TheBoss.EmployeeID = Thereport.MangerID
WHERE
TheBoss.LastName='Huntington' AND TheBoss.FirstName ='Karla'
他为什么要写个自连接的查询呢?
为什么不能直接
SELECT
Thereport.EmployeeID,
Thereport.JobTitle,
Thereport.LastName,
Thereport.FirstName,
From
HumanResources.Emplyee2 as TheBoss
WHERE
TheBoss.LastName='Huntington' AND TheBoss.FirstName ='Karla'
所以我会提出疑问是不是where只能跟主键配合 查询性能才好?
SELECT Name
FROM Production.product
WHERE ProductID=365ProductID是product表的主键。类似这样的例子很多。还有有个我没弄懂的例子,书上在讲述处理分层数据的时候 有段这样的代码
USE AdventureWorks2008SELECT
Thereport.EmployeeID,
Thereport.JobTitle,
Thereport.LastName,
Thereport.FirstName,
From
HumanResources.Emplyee2 as TheBoss
JOIN
HumanResources.Emplyee2 as Thereport
ON
TheBoss.EmployeeID = Thereport.MangerID
WHERE
TheBoss.LastName='Huntington' AND TheBoss.FirstName ='Karla'
他为什么要写个自连接的查询呢?
为什么不能直接
SELECT
Thereport.EmployeeID,
Thereport.JobTitle,
Thereport.LastName,
Thereport.FirstName,
From
HumanResources.Emplyee2 as TheBoss
WHERE
TheBoss.LastName='Huntington' AND TheBoss.FirstName ='Karla'
所以我会提出疑问是不是where只能跟主键配合 查询性能才好?
TheBoss.EmployeeID = Thereport.MangerID你要注意这里的连接条件。
2、join的关联列,推荐是int格式的,性能好。
3、语句用自关联是为了增加筛选条件,确定两个列相等的一个条件。
也有其他方式的实现的语句,也许书中只是为了举例子。
用主键当然能加快查询速度,但它不是唯一的选择,只是查询要求是这样罢了.同一表的连接,也是业务需求的原因,这个要结合具体数据来看,比如,有这样一个表:
tb
id Parentid name
1 0 'AA'
2 1 'BB'
3 1 'cc'
4 0 'DD'如果要求查询某个父下面的所有子,则用自连接:select a.name as parentname,b.name as subname from tb a inner join tb b on a.id=b.Parentid where a.parentid=0
insert into tb select 1,0,'AA'
insert into tb select 2,1,'BB'
insert into tb select 3,1,'cc'
insert into tb select 4,0,'DD'
go
select a.name as parentname,b.name as subname from tb a inner join tb b on a.id=b.Parentid where a.parentid=0
/*
parentname subname
---------- ----------
AA BB
AA cc(2 行受影响)
*/
go
drop table tb
你也看了,说的是分层查询。如4,6楼所说。然后就是WHERE 后面可以有任何字段的,不是只可以有主键,只是主键有好处。如2楼所说。
为了提高查询效率 一般需要建索引。 聚簇索引、唯一索引、非聚簇索引等都是提高查询效率的优选方法。另外 where 后面的条件 还跟 索引列的先后有关。