





b,可以用如下语句,将count换成sum:
或者:select name,avg(score) from stu group by name having sum(score<60)>1;写法6. 子查询 a. where 子查询:把内层查询的结果作为外层查询的比较条件。eg:查询最新的商品select max(goods_id),goods_name from goods;报错:Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause可以用这样的查询:select goods_id,goods_name from goods where goods_id=(select max(goods_id) from goods); 查询每个栏目下的最新商品: select goods_id,cat_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id);
b.from 型子查询:把内层查询结果当成临时表,供外层sql再次查询(临时表必须加一个别名)查询每个栏目下最新商品 select * from (select goods_id,cat_id,goods_name from goods order by cat_id asc,goods_id desc) as t group by cat_id;5中 查询挂科两门及以上同学的平均分 select sname from (select name as sname from stu) as tmp; c. exists子查询:把外层查询的结果变量,拿到内层,看内层的查询是否成立查询有商品的栏目:select cat_id,cat_name from category where exists (select * from goods where goods.cat_id=category.cat_id);
由于没有条件,将会查出所有栏目: select cat_id,cat_name from category where exists (select * from goods); 用in也可实现7. in(v1,v2-----) between v1 and v2(包括v1,v2) like(%,_) order by column1(asc/desc),column2(asc/desc)先按第一个排序,然后在此基础上按第二个排序8. union 把两次或多次查询结果合并起来两次查询的列数一致 ,对应列的类型一致列名不一致时,取第一个sql的列名如果不同的语句中取出的行的值相同,那么相同的行将会合并(去重复),如果不去重用union all来指定 如果子句中有order by,limit 子句必须加(),select * from ta union all select * from tb;
取第四栏目商品,价格降序排列,还想取第五栏目商品,价格也按降序排列 (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); 推荐放到所有子句之后,即:对最终合并的结果来排序 ( 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);
9. 连接查询 左连接: select column1,column2,columnN from ta left join tb on ta列=tb列[此处表连接成一张大表,完全当成普通的表看] where group,having....照常写 右连接: select column1,column2,columnN from ta right join tb on ta列=tb列[此处表连接成一张大表,完全当成普通的表看] where group,having....照常写 内连接: select column1,column2,columnN from ta inner join tb on ta列=tb列[此处表连接成一张大表,完全当成普通的表看] where group,having....照常写 左连接以左表为准,去右表找匹配数据,没有匹配的列用null补齐,有多个的均列出如有下两表:

select boy.*,girl.* from boy left join girl on boy.flower=girl.flower;结果:
左右连接可以相互转化,推荐用左连接,数据库移植方便 内连接:查询左右表都有的数据(左右连接的交集) 选取都有配对的组合 
左或右连接查询实际上是指定以哪个表的数据为准,而默认(不指定左右连接)是以两个表中都存在的列数据为准,也就是inner join mysql不支持外连接 outer join 即左右连接的并集当多个表中都有的字段要指明哪个表中的字段 三个表连接查询 brand,goods,categoryselect g.goods_id,cat_name,g.brand_id,brand_name,goods_name from goods g left join brand b on b.brand_id=g.brand_id left join category c on g.cat_id=c.cat_id; 作者 ljfbest bitsCN.com
