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

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:子查询查不到结果,结果为真。

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