1.子查询
select c_id from order where or_num in (select or_num from orderitem where p_id = 'tt');
select c_name,c_contact from cust where c_id in (select c_id from order where o_num in ( select o_num from orderitem where p_id='aa'));
2.联结
联结是一种机制,用来在一条select语句中关联表,使用特殊的语法,可以联结多个表返回一组输出,联结在运行时关联表中正确的行。联结由mysql根据需要建立,它存在于查询的执行当中。
select v_name,p_name,p_price from v,p where v.v_id = p.v_id order by v_name,p_name;
where 后面跟联结条件,没有联结条件的表关系返回的结果回事笛卡尔积,行数等于表一行数乘以表二行数。
(1)内部联结
select v_name,p_name,p_price from v inner join p on v.v_id=p.v_id;
select p_name,v_name,p_price,qua from orderitems,p,v where p.v_id = v.v_id and orderitem.p_id = p.p_id and o_num = 1;
(2)自然联结
select c.*,o.o_num,o.o_date,oi.p_id,oi.qua,oi.i_price from cust as c,order as o,orderitem as oi where c.c_id = o.o_id and oi.o_num = o.o_num and p_id = 2;
(3)外部联结
select c.c_id,o.o_num from c left outer join o on c.c_id = o.c_id;
此语句表示左边的表选择所有行。right outer join 右边的表选择所有行
注:使用联结和联结的条件如下:
。注意所使用的联结类型,一般用内部联结
。使用中要保证正确的使用联结条件,否则会返回不正确的数据
。保证有联结条件,防止笛卡尔积
。在一个联结中可以包含多个表,对于每一个联结可采取不同的联结类型,测试时应分别测试,有利排查问题