分类 隐式内连接:select * from A,B where 条件; 显式内连接:select * from A inner join B on 条件;(效率更高)
区别 使用关键字 inner join 前者在笛卡尔集的基础上筛选,后者在原始表上筛选
练习
隐式内连接:select*from A,B where 条件;select*from category c,products p where c.cid = p.category_id;
显式内连接:select*from A innerjoin B on 条件;(效率更高)
select*from category c innerjoin products p on c.cid = p.category_id;
select*from province,city;select*from province p innerjoin city c on p.pid = c.pid_fk;
外连接查询
什么是外连接查询 两个表中选一个表将数据全部输出,另一个表没有对应数据则输出NULL
分类 左外连接 select * from A left outer join B on 条件; 以左表为主,左表中的数据全部输出,右表中如果没有同等的数据则补NULL 右外连接 select * from A right outer join B on 条件; 以右表为主,右表中的数据全部输出,左表中如果没有同等的数据则补NULL
# 外连接select*from province p innerjoin city c on p.pid = c.pid_fk;# 左外连接select*from province p leftouterjoin city c on p.pid = c.pid_fk;# 右外连接select*from province p rightouterjoin city c on p.pid = c.pid_fk;
子查询
什么叫子查询 select的嵌套,一个select的查询结果作为另一个select查询语法的一部分
案例 在商品表中查询属于电子分类的商品
select*from product where cid =1select cid from category where cname='电子'select*from product where cid =(select cid from category where cname='电子')