exists子查询

exists:

只注重子查询是否有返回行,如查有返回行结果为真,否则为假,并不适用子查询的结果,仅使用测试子查询是否有返回结果

语法:

if exists (子查询)

  begin     --如果有多条语句时需要适用begin  end 语句如果只有一条语句时begin end可以省略

    语句块

  end

例子:

if exists(select * from sysdatabases where name='E_Market')

drop database E_Market

go 

--exists子查询
--一次性购买“手机数码”产品的数量超过3个的,消费金额打8折
--根据已知项查询未知项
--【1】根据类别名称查询类别编号
use E_Market
go
select SortId from CommoditySort where SortName='手机数码'
--[2]根据1中类别的编号编号查询商品编号
select * from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)

--[3]根据2中得到的商品编号去查询订单表中的购买数量超过3个的用户信息
select * from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3

--[4]购买超过3个的用户的付款金额打8折
if exists(select * from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3)
begin
--对付款金额打八折
update OrderInfo set ParMoney=ParMoney*0.8
where CommodityId in
(
select CommodityId from OrderInfo where CommodityId in
(
select CommodityId from CommodityInfo where SortId=
(
select SortId from CommoditySort where SortName='手机数码'
)
) and Amount > 3
)
end

--通常会使用not exists对结果进行子查询的结果进行取反
--exists:子查询查到记录,结果为真否则结果为假
--notexists:子查询查不到结果,返回为真,子查询查到结果返回为假

转载于:https://www.cnblogs.com/zhangxudong-cnblogs/p/10858873.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值