有表test如下
id pid(上级ID)
1  0
2  1
3  3(上级ID是自己)
4  3
5  0
6  5sql语句如下:
delete t
from test t
where not exists(select id from test where id=t.pid)我的目的是删除没有上级的记录我的理解是
先删除id=1的记录(因为他的pid=0,id=0的记录不存在)
然后删除id=2的记录(因为他的pid=1,id=1的记录在上一步已经删除了)

最后的结果应该是
3  3
4  3
才对但实际执行的结果却是
2  1
3  3(上级ID是自己)
4  3
6  5
只删除了pid=0的记录这是怎么回事,应该怎样写才符合我的要求呢?请指教。谢谢

解决方案 »

  1.   

    你这要多步的while exists (
      select 1
      from test t 
      where not exists(select id from test where id=t.pid) 
      )
    delete t 
    from test t 
    where not exists(select id from test where id=t.pid) 
      

  2.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(我是小F,向高手学习)
    -- Date    :2009-09-04 10:50:30
    -- Verstion:
    --      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
    -- Nov 24 2008 13:01:59 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([id] int,[pid] int)
    insert [tb]
    select 1,0 union all
    select 2,1 union all
    select 3,3 union all
    select 4,3 union all
    select 5,0 union all
    select 6,5
    --------------开始查询--------------------------
    while exists (select 1  from tb t where not exists(select id from tb where id=t.pid))
    begin
    delete 
      t 
    from 
      tb t 
    where not exists(select id from tb where id=t.pid)
    end
    select * from tb
    ----------------结果----------------------------
    /*id          pid
    ----------- -----------
    3           3
    4           3(2 行受影响) 
    */
      

  3.   

    果真是高手。Yang_,您的方法可行。不过如果表非常大的话,效率就太低了吧。
    对了,问一下,bom是什么?见笑,见笑
      

  4.   

    BOM没有什么不好!有时非得用不可!