一些简单的sql语句,比如说 现在数据库中有10记录,要求你写一个语句保留第二条和第五条记录,将其他的记录全部删除。

解决方案 »

  1.   


    --举例如下
    SQL> delete emp
      2   where not exists (select 1 from
      3   (select rownum rn,empno from emp) t
      4   where t.empno=emp.empno and t.rn in(2,5));已删除12行。SQL> select * from emp;     EMPNO ENAME                JOB                       MGR HIREDATE          
    ---------- -------------------- ------------------ ---------- --------------    
           SAL       COMM     DEPTNO                                                
    ---------- ---------- ----------                                                
          7499 Allen                SALESMAN                 7698 20-2月 -81        
          1600        300         30                                                
                                                                                    
          7654 Martin               SALESMAN                 7698 28-9月 -81        
          1250       1400         30                                                
                                                                                    SQL> rollback;回退已完成。
      

  2.   

    第一步:
    原数据编号rownum
    select rownum rm,id from students
    第二步:
    查询编号2、5所对应的id
    第三步:
    执行删除且where条件2、5所对应的id不删除delete from students where id not in(select t.id from (select rownum rm,id from students) t where t.rm in(2,5));
      

  3.   

    delete emp
           where not exists (select 1 from
               (select rownum rn,empno from emp) t
               where t.empno=emp.empno and t.rn in(2,5));
      

  4.   


    最好封装成一个通用的语句,如果想保留第1条和第3条记录,那么SQL语句就要做相应的修改
      

  5.   

    一楼正解,通过rownum得到你需要的记录,再加上not exists 判断
      

  6.   

    就是通过伪列 rownum,然后删除不是第2和第5 就可以了啊
      

  7.   

    请问为什么where子句中的连表查询语句中只用写 t表而不用连上emp表?
    因为
    select 1 from
    (select rownum rn,empno from emp) t
    where t.empno=emp.empno and t.rn in(2,5);
    单独执行的时候是不成功的,因为from子句中少了个表,
    而为什么在你的delete中作where查询子句却可以用?
      

  8.   

    delete  from 
    emp01 where empno not in(select a.empno from emp01,(select row_number() over(order by empno)  r,emp01.* from emp01)a
    where emp01.empno=a.empno
    and a.r not in(2,5)
    )