MySql实验3——高级查询语句

本文详细解释了SQL中的嵌套查询(包括IN、单层EXISTS和双层EXISTS)以及集合查询,以查找特定客户订购的特定产品(如牡丹汽车股份有限公司的放像机),并展示了如何查找共享购买记录的顾客如曹康和阿迪的共同零件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. IN嵌套查询

查询订购了“牡丹汽车股份有限公司”制造“放像机”的顾客。

Select * from customer where c_custkey in 
(select o_custkey from orders,supplier,part,lineitem,partsupp 
where s_name=”牡丹汽车股份有限公司” 
and p_name=”放像机” 
and p_partkey=l_partkey 
and l_suppkey=s_suppkey 
and o_orderkey=l_orderkey);

 2.单层EXISTS嵌套查询

查询没有购买过“牡丹汽车股份有限公司”制造“放像机”的顾客

Select * from c_ where not exists
(select * from orders,supplier,part ,lineitem ,partsupp 
where s_name=”牡丹汽车股份有限公司” 
and p_name=”放像机” 
and p_partkey=l_partkey 
and l_suppkey=s_suppkey 
and o_orderkey=l_orderkey 
and c_custkey=o.custkey);

3. 双层EXISTS嵌套查询

查询至少购买过顾客“王雅奇”购买过的全部零件的顾客姓名(不存在王雅奇购买过而C客户没有买过的零件)(注意别名的前缀)

Select distinct c_name from customer c 
where not exists
 (select * from customer c1,lineitem l,orders o 
where c1.c_name=”王雅奇” 
and c1.c_custkey=o.o_custkey 
and o.o_orderkey=l.l_orderkey 
and not exists 
(select * from lineitem l1,orders o1 
where c.c_custkey=o1.o_custkey 
and l1.l_partkey=l.l_partkey 
and l1.l_orderkey=o1.o_orderkey));

4. 集合查询

查询顾客“曹康”和“阿迪”都订购过的全部零件的信息

Select * from part ,customer,orders,lineitem ,partsupp ,supplier 
where c_name=”曹康” 
and c_custkey=o.custkey 
and l_partkey=ps_partkey 
and o_orderkey=l_orderkey 
and l_suppkey=s_suppkey 
and ps_partkey=p_partkey 
INTERSECT 
(Select * from part ,customer,orders,lineitem ,partsupp ,supplier 
where c_name=”阿迪” 
and c_custkey=o.custkey 
and l_partkey=ps_partkey 
and o_orderkey=l_orderkey 
and l_suppkey=s_suppkey 
and ps_partkey=p_partkey);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值