【SQL解惑】谜题18:广告信件

一、创建并插入数据
create  table  Consumers
(
con_name  varchar ( 20 )  not  null,
address  varchar ( 10 )not  null,
con_id  int  not  null,
fam  int
)
insert  into  Consumers ( con_name , address , con_id , fam )
values ( 'Bob' , 'A' , 1 ,null),
( 'Joe' , 'B' , 3 ,null),
( 'Mark' , 'C' , 5 ,null),
( 'Mary' , 'A' , 2 , 1 ),
( 'Vickie' , 'B' , 4 , 3 ),
( 'Wayne' , 'D' , 6 ,null)

二、查询语句
1、解惑一
delete  from  Consumers
  where  fam  is  null
    and  ( select  COUNT (*)
               from  Consumers  as  c2
              where  c1 . address  =  c2 . address )  >  1
2、解惑二
delete  from  Consumers
   from  Consumers  as  c1
  where  fam  is  null
    and  exists
        ( select  *
               from  Consumers  as  c2
              where  c1 . con_id  <>  c2 . con_id
                and  c1 . address  =  c2 . address
                and  c2 . fam  is  not  null)
3、解惑三
delete  from  Consumers
   from  Consumers  as  c1
  where  c1 . fam  is  null
    and  exists  ( select  *
                          from  Consumers  as  c2
                         where  c2 . fam  =  c1 . con_id )
三、改进
select  C1 .*
   from  Consumers  as  c1
except
select  C1 .*
   from  Consumers  as  c1
  where  c1 . con_id  in  ( select  fam
                            from  Consumers  as  c3
                           where  c3 . address  =  c1 . address )
由于语句的话只要筛选出需要删除的数据,然后再用except去反选即可。










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值