有一个表,两个字段:id,id_foreign.其中id_foreign作为外键引用id的值(也就是自相关)。现在有一个问题,id_foreign引用的主键不存在,请问如何查询出这些不存在的主键并把这条记录删除?在线等求助,谢谢!

解决方案 »

  1.   

    delete tb
    where not exists(
      select 1
      from tb t
      where t.id_foreign=tb.id)
      

  2.   

    你别着急,现在说的有点看不懂,你自己懂了,说得在明白点haoma?
      

  3.   

    比如:
    1,null
    2,1
    3,1
    4,2
    第四条记录id_foreign的值为2,但是整个表没有id为2的记录,就是如何查出第四条记录
    注:id_foreign为null不需要查出
      

  4.   

    你的意思是:
    1,null
    3,1
    4,3
    5,4
    6,2
    把6,2这条删掉是吗?我要下班了,回家给你看看。
      

  5.   

    delete form table tb
    where tb.id_foreign not in{
     select tb1.id from table tb1
    }
      

  6.   


    delete tb
    where id_foreign not in(select id_foreign from tb where id=id_foreign)