我看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只能跟主键配合 查询性能才好?

解决方案 »

  1.   

    ON
        
      TheBoss.EmployeeID = Thereport.MangerID你要注意这里的连接条件。
      

  2.   

    不是的,where 后面可以跟任何的属性来查询,
      

  3.   

    表中肯定 EmployeeId 和 MangerID 吧!书上的查询是为了找到管理 Huntington.Karla 员工的管理者的信息。
      

  4.   

    1、主键索引是其他索引的基础,效率相对很高,所以主键列匹配也是首选
    2、join的关联列,推荐是int格式的,性能好。
    3、语句用自关联是为了增加筛选条件,确定两个列相等的一个条件。
    也有其他方式的实现的语句,也许书中只是为了举例子。
      

  5.   

    嗯,是,where 后面可以跟任何的属性来查询,
      

  6.   

    当然不是.
    用主键当然能加快查询速度,但它不是唯一的选择,只是查询要求是这样罢了.同一表的连接,也是业务需求的原因,这个要结合具体数据来看,比如,有这样一个表:
    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
      

  7.   

    create table tb(id int,Parentid int,name varchar(10))
    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
      

  8.   

    看到楼上的都回答完了,主要还是连接条件。
    你也看了,说的是分层查询。如4,6楼所说。然后就是WHERE 后面可以有任何字段的,不是只可以有主键,只是主键有好处。如2楼所说。
      

  9.   

    著书的人都是 学者。你要做个 实践者。 千万不要去抠书上写的。 主键列在SQL 里默认是聚簇索引,
    为了提高查询效率 一般需要建索引。 聚簇索引、唯一索引、非聚簇索引等都是提高查询效率的优选方法。另外 where 后面的条件 还跟 索引列的先后有关。