第14章:使用子查询。
子查询是镶嵌在其他查询里面,相当其他的select查询的条件来。
P91
select order_num from where prod_id='tnt2'; #检索条件为prod_id=tnt2的order_num#
select cust_id from orders where order_num in (20005,20007); #检索满足条件 order_num在范围(20005,20007)的cust_id#
select cust_id from orders where order_num in (select order_num from orderitems where prod_id ='tnt2' ); #检索 满足条件:///在表orderitems中满足prod_id=tnt2 的order_num,orderitems.order_num =orders.order_num /// 这部分的order_num在orders中对应的cust_id # ##实际上,就是上面的两个语句组合而成的##
P92
select cust_name,cust_contact from customers where cust_id in (10001,10004); #检索表customers满足客户Id在范围(10001,10004)内,对应的cust_name,cust_contact #
select cust_name,cust_contact from customers where cust_id in (select cust_id from orders where cust_num in (select cust_num from orderitems where prod_id ='tnt2') ); #镶嵌了两个子查询,从最里面的括号的条件开始运行#
P94
select count(*) as orders from orders where cust_id=10001; #检索cust_id=10001的个数#
select cust_name,cust_state,(select count(*) from orders where orders.cust_id =customers.cust_id) as orders from customers order by cust_name ; #关联两个表,检索满足条件orders.cust_id = customers.cust_id 的行数(count(*)),cust_name,cust_state #
注意:关联多个表的时候,要指明列的时候,表示哪个表哪个列的时候:表点列(如customers.cust_name) !!!