首页 > 数据库技术 > 详细

mysql之3种子查询

时间:2015-05-12 18:32:52      阅读:263      评论:0      收藏:0      [点我收藏+]

  mysql有3种子查询,包括,where型,from型和exists型。

  where型子查询

  where后面跟的是条件表达式,条件为真时便取出该行,where型子查询是指内层的select语句的查询结果集充当外层select语句的where后面的条件表达式,比如,查询每个栏目下的最新的商品,select goods_id,cat_id,goods_name from goods where goods_id in (select max(goods_id) from goods group by cat_id); 注意内层select语句只能书写一列,如果是多列就会报错,比如,select max(goods_id),cat_id from goods group by cat_id)多了cat_id这一列是不行的。技术分享

  from型子查询

  from型子查询是指内层的select语句的查询结果集充当外层select语句的新的表,比如,还是查询每个栏目下的最新的商品,select * from (select goods_id,cat_id,goods_name from goods order by goods_id desc,cat_id asc) as tmp group by cat_id;内层的表必须用as另取名称,不然会报错。

技术分享

  exists型子查询

  exists型子查询和in用法相似,比如,查询有商品的栏目,select * from category where exists (select * from goods where goods.cat_id=category.cat_id);也可以用in实现,select * from category where cat_id in (select cat_id from goods);

技术分享

技术分享

mysql之3种子查询

原文:http://www.cnblogs.com/museluo/p/4498107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!