简单的sql查询

来源:互联网 发布:亚马逊云计算培训 编辑:程序博客网 时间:2024/05/15 10:34

一般的工作中不会涉及到太难得sql查询语句,无非是多表关联查询,多表关联主要有三种查询方式
(一)内连接查询
内连接查询,是查询出两张表中必然有关联的数据,没有关联的数据不能查询出
语法:select 字段 from 表1 inner join 表2 on 条件
示例:查询出商品的信息和商品所属的类别信息
select * from product p inner join category c on p.cid=c.cid

隐式内连接:select 字段 表1,表2… where 条件
示例:查询出商品的信息和商品所属的类别信息
select * from product p,category c where p.cid=c.cid
(二)外连接
左外连接,是查询出左表的全部内容,右表中只查出与左表有关联的数据
语法:select 字段 from 左表 left [outer] join 右表 on 条件
示例:查询出所有的类别信息,如果该类别有商品则一并查出
select * from category c left join product p on c.cid=p.cid;

右外连接,是查询出右表的全部内容,左表中只查询出与右表有关联的数据
语法:select 字段 from 左表 right [outer] join 右表 on 条件
示例:查询出所有的类别信息,如果该类别有商品则一并查出
select * from product p right join category c on c.cid=p.cid;
(三)子查询
个人认为子查询就是先使用sql查询出来需要的数据值,让后将这条sql当作该值放进需要查询的sql语句中。
示例:查询商品价格大于总商品平均价格的商品
分步骤查:
查询平均价格:select avg(price) from product;
查询商品信息:
select * from product where price>2299;
使用子查询:
select * from product where price>(select avg(price) from product);
也就是select avg(price) from product;相当于是2299.