码迷,mamicode.com
首页 > 数据库 > 详细

测试那些事儿—SQL server exists子查询

时间:2019-05-28 17:08:30      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:upd   超过   select   end   技术   数码   image   alt   width   

exists子查询

技术图片

 

--一次性购买“手机数码”产品的数量超过三个的消费金额打8折

--根据已知项查询未知项

--【1】根据类别名称查询类别编号

select sortid from commoditysort where sortname=‘手机数码‘

--【2】根据类别编号查询商品编号

select commodityid from commodityinfo 

where sortid=

(select sortid from commoditysort where sortname=‘手机数码‘)

--【3】根据商品编号去查询订单表中的购买数量超过三个的订单信息

select commodityid from orderinfo

where commodityid in  --注意此处为in还是=

(

select commodityid from commodityinfo 

where sortid=

(select sortid from commoditysort where sortname=‘手机数码‘))

and amount >3

--【4】购买超过3个的用户的付款金额打8折

if exists(

select commodityid  from orderinfo

where commodityid in  --注意此处为in还是=

(

select commodityid from commodityinfo 

where sortid=

(select sortid from commoditysort where sortname=‘手机数码‘))

and amount >3

)

begin 

 --对付款金额打8折

    update orderinfo set paymoney = paymoney * 0.8

    where commodityid in

    (

select amount from orderinfo

where commodityid in  --注意此处为in还是=

(

select commodityid from commodityinfo 

where sortid=

(select sortid from commoditysort where sortname=‘手机数码‘))

and amount >3

)

end

--通常会使用not exists 对子查询结果进行取反

--exists:子查询查到记录,结果为真,否则结果为假

--not exists:子查询查不到结果,结果为真。

 

测试那些事儿—SQL server exists子查询

标签:upd   超过   select   end   技术   数码   image   alt   width   

原文地址:https://www.cnblogs.com/mgg520813/p/10935810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!