常用MS SQL数据查询-2016

1、多表联合查询,主表User~从表UserAddress(一对多关系),重复记录只保留1条(id最小或最大)

     (1)查询子表,过滤重复记录

               select * from UserAddress a  
               where not exists (select 1 from UserAddress where a.UserID=UserID and id<a.id)

               -这里的 id<a.id 表示对符合条件 a.UserID=UserID记录 进行比较,

                   例如这里符合条件的id有 1, 3, 5, 6, 13,当用小于"<"比较,最小为1,当ID为1时查询结果为空,

                  即主表id=1时 where not exists ( ...) 返回真

                -如果 id>a.id 用大于号">"比较,最大为13,当ID为13时没有任何数比它更大,查询结果为空,

                  即主表id=13时 where not exists ( ...) 返回真

      (2)联合查询主、从表,过滤重复记录

               select User.id, UA.addTel, UA.addCountry, UA.addAddressLine1 from [User] left join

                   (select UserID, addtel, addCountry, addAddressLine1 from UserAddress a 

                      where not exists (select 1 from UserAddress where a.UserID=UserID and id<a.id)) as UA

               ON User.id=UA.UserID



 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值