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);