name date
张三 2009-12-31
李四 2008-8-13
王五 2009-7-25
张三 2010-2-23
李四 2008-9-15查同名的日期最大的记录select *
from tb t
where exists(
select 1
from tb
where t.name=name and date>t.date
 
以上查询对么?看到sql_sf还有小f等高手用带exists嵌套查询的自连接,请讲一下1.如何理解带exists子查询的自连接2.是先从子查询看还是从父查询看

解决方案 »

  1.   

    应该是:
    select *
    from tb t
    where not exists(
    select 1
    from tb
    where t.name=name and date>t.date
    1、exsists 只判断记录是否存在
    2、先看父查询,再看子查询
    因为子查询的判断条件一般依赖父查询特定行字段值。如:date字段~~
      

  2.   

    解释一下语句呀!
    4楼的语句解释是:查看表t中的所有列,条件是不在两个表关联切tb的date>t的date是这样不
      

  3.   

    刚才试了一下,这个自连接,只能比2条记录以上的?如果表中只有一个name的,结果集里不显示啊,现在的结果集就不显示'王五'的
      

  4.   

    是not exists
    不是exists
    你换成not exists看看有结果不?
      

  5.   


    if OBJECT_ID('tb') is not null
    drop table tb
    go
    create table tb 
    (
    name nvarchar(50),
    date datetime
    )
    insert into tb 
    select '张三', '2009-12-31' union all
    select '李四', '2008-8-13' union all
    select '王五', '2009-7-25' union all
    select '张三', '2010-2-23' union all
    select '李四', '2008-9-15' select * from tb as t
    where not exists(select DATE from tb where t.date<date and t.name=tb.name)