当前位置: 代码迷 >> Sql Server >> 小弟我是SQL盲,求一SQL语句
  详细解决方案

小弟我是SQL盲,求一SQL语句

热度:80   发布时间:2016-04-27 12:57:23.0
我是SQL盲,求一SQL语句
表一: SBCRKBH 

表二: SBKCJL

2表都有主键列 DH (对应关系是:SBCRKBH.DH=SBKCJL.DH)。

现在情况是,好多记录,DH 在 SBKCJL 中存在,在 SBCRKBH 没有了, 目的:

一、查询出 DH 在 SBKCJL 中存在,而 SBCRKBH 中没有的记录
二、删除 SBKCJL 的记录,条件是:DH 在 SBKCJL 中存在,而 SBCRKBH 中没有 





------解决方案--------------------
SQL code
1,select * from SBKCJL where DH not in(select DH from SBCRKBH)
------解决方案--------------------
SQL code
2,delete from SBKCJL where DH not in(select DH from SBCRKBH)
------解决方案--------------------
select * 
from SBKCJL 
where DH not in(select DH from SBCRKBH)


delete 
from SBKCJL 
where DH not in(select DH from SBCRKBH)

------解决方案--------------------
select * 
from SBKCJL 
where DH not in(select DH from SBCRKBH)


delete 
from SBKCJL 
where DH not in(select DH from SBCRKBH)

------解决方案--------------------
SQL code
select *  from SBKCJL  where DH not in(select DH from SBCRKBH)delete  from SBKCJL  where DH not in(select DH from SBCRKBH)
------解决方案--------------------
一、查询出 DH 在 SBKCJL 中存在,而 SBCRKBH 中没有的记录

select t.* from SBKCJL t where not exists (select 1 from SBCRKBH n where n.dh = t.dh)
select t.* from SBKCJL t where dh not in (select dh from SBCRKBH)

二、删除 SBKCJL 的记录,条件是:DH 在 SBKCJL 中存在,而 SBCRKBH 中没有

delete SBKCJL from SBKCJL t where not exists (select 1 from SBCRKBH n where n.dh = t.dh)
delete SBKCJL from SBKCJL t where dh not in (select dh from SBCRKBH)

------解决方案--------------------
1、select *
from SBKCJL
where DH not in(select DH from SBCRKBH)


2、delete
from SBKCJL
where DH not in(select DH from SBCRKBH)

------解决方案--------------------
SQL code
--一、查询出 DH 在 SBKCJL 中存在,而 SBCRKBH 中没有的记录--二、删除 SBKCJL 的记录,条件是:DH 在 SBKCJL 中存在,而 SBCRKBH 中没有--1.SELECT * FROM SBKCJL AS aWHERE NOT EXISTS(SELECT 1 FROM SBCRKBH AS x WHERE x.DH=a.DH)--2.DELETE a FROM SBKCJL AS aWHERE NOT EXISTS(SELECT 1 FROM SBCRKBH AS x WHERE x.DH=a.DH)
  相关解决方案