1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null 可以在num上设
1、子查询:
子查询就是在原有的查询语句中,嵌入新的查询,来得到我们想要的结果集。一般根据子查询的嵌入位置分为,where型子查询,from型子查询
1、Where 型子查询: 把内层查询的作为外层查询的比较条件
典型语法:
select * from tableName
where colName = (select colName from tbName where ….)
{where colName in (select colName from tbName where ..)}
典型题:查询最大商品,最贵商品
查询出最新一行商品(以商品编号最大为最新,用子查询实现)
select goods_id,goods_name from goods where goods_id=(select max(goods_id) from goods);
每个栏目最贵的商品
Select goods_id,cat_id,goods_name,shop_price from goods where shop_price in (select max(shop_price) from goods group by cat_id);
2、From 型子查询: 把内层的查询结果当成临时表,供外层sql再次查询
给临时表加一个别名 as
典型语法:
select * from (select * from tableName where …) where….
典型题:查询栏目下最新/最贵商品1增 2删 3改 4查 1where各种条件查询场合 2group常用语统计场合 3having 4order by各种排序场合 5limit 在语句的最后起到限制条目的作用 5模糊查询Like 1、增 插入单行或者多行 insert into msg (id,title,name,content) values (1,‘又来了’,‘李四’
试查询两门及两门以上不及格同学的平均分(where、from子查询)
select name,avg(score) from stu where name in (select name from (select name,sum(score<60) as h from stu group by name having h>1) as tmp) group by name;
3、Exists 型子查询:外层sql查询的代入内层sql查询,要使内层查询能够成立 。查询可以与in型子查询互换,但效率要高.
典型语法:
select * from tablename
where exists(select * from tableName where …)
典型题:查询有商品的栏目
Select cat_id,cat_name from category where exists (select * from goods where goods.cat_id = category.cat_id);
2 、Union:联合
作用: 把2次或多次查询结果合并起来
要求:两次查询的列数一致
推荐:查询的每一列,相对应得列类型也一样
可以来自于多张表,多次sql语句取出的列名可以不一致,此时,以第1个sql的列名为准
如果不同的语句中取出的行,有完全相同的(每个列的值都相同),那么相同的行将会合并(去重复).
如果不去重复,可以加all来指定 union all
想取第4栏目的商品,价格降序排列,还想取第5栏目的商品,价格也降序排列
(select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 4 order by shop_price desc) union (select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 5 order by shop_price desc) order by shop_price desc;
取第3个栏目价格前3高的商品和第4个栏目价格前2高的商品,union来实现
(Select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 3 order by shop_price desc limit 3) union
(Select goods_id,cat_id,goods_name,shop_price from goods where cat_id = 4 order by shop_price desc limit 2)