mysql 子查询
2014-05-07 14:31
141 查看
1.使用where子查询
查询每个栏目下最新的商品:(最终查询结果是多行 内层sql返回是多行单列)
select goods_id,goods_name,cat_id from goods where goods_id in (select max(goods_id) from goods group by cat_id );
查询(所有栏目中)最新的商品:(最终查询结果是单行 内层sql返回单行单列)
select goods_id,goods_name,cat_id from goods where goods_id = (select ma
x(goods_id) from goods );
总结:
注意区分上述两个应用以及语句。
where子查询,是指把内层sql查询的结果作为外层查询的比较条件
典型的就是查询最新的商品,最贵的商品
如果 where 列 =(内层sql) 则内层sql只返回‘单行单列,单个值’
如果 where 列in(内层sql) 则内层sql只返回‘单列,可以多行’
2.使用from子查询
查询每个栏目下最新的商品:
select * from (select goods_id,goods_name,cat_id from goods order by cat_id asc,goods_id desc ) as tmp group by cat_id;
注意:一定要有as tmp 否则语法错误Every derived table must have its own alias:每个派生出来的表都要有自己的别名。
3.exists子查询
只把category中的里面有商品的栏目取出来
select cat_id,cat_name from category where exists (select * from goods wh
ere goods.cat_id = category.cat_id);
select cat_id,cat_name from category where exists (select * from goods wh
ere cat_id = category.cat_id);也行
查询每个栏目下最新的商品:(最终查询结果是多行 内层sql返回是多行单列)
select goods_id,goods_name,cat_id from goods where goods_id in (select max(goods_id) from goods group by cat_id );
查询(所有栏目中)最新的商品:(最终查询结果是单行 内层sql返回单行单列)
select goods_id,goods_name,cat_id from goods where goods_id = (select ma
x(goods_id) from goods );
总结:
注意区分上述两个应用以及语句。
where子查询,是指把内层sql查询的结果作为外层查询的比较条件
典型的就是查询最新的商品,最贵的商品
如果 where 列 =(内层sql) 则内层sql只返回‘单行单列,单个值’
如果 where 列in(内层sql) 则内层sql只返回‘单列,可以多行’
2.使用from子查询
查询每个栏目下最新的商品:
select * from (select goods_id,goods_name,cat_id from goods order by cat_id asc,goods_id desc ) as tmp group by cat_id;
注意:一定要有as tmp 否则语法错误Every derived table must have its own alias:每个派生出来的表都要有自己的别名。
3.exists子查询
只把category中的里面有商品的栏目取出来
select cat_id,cat_name from category where exists (select * from goods wh
ere goods.cat_id = category.cat_id);
select cat_id,cat_name from category where exists (select * from goods wh
ere cat_id = category.cat_id);也行
相关文章推荐
- MySQL入门笔记 —— 019 where型子查询
- MYSQL的UPDATE子查询,UPDATE时避免使用子查询
- mysql子查询
- Mysql——子查询
- MySQL数据高级查询之连接查询、联合查询、子查询
- Mysql子查询
- MYSQL的UPDATE子查询,UPDATE时避免使用子查询
- MySQL数据高级查询之连接查询、联合查询、子查询
- [MYSQL -14]使用子查询
- windows下的MySQL-子查询
- MySql中的子查询
- MySQL基础(四)- 连接以及子查询
- MYSQL的UPDATE子查询,UPDATE时避免使用子查询
- 40.笔记 MySQL学习——带关系比较运算符的子查询
- mysql(4) 子查询
- MySQL 使用profile分析慢sql,group left join效率高于子查询
- MySql--DML语句、简单查询和子查询
- mysql (dml) 链表查询 和 子查询
- MySql中常见的三种业务子查询
- 聊聊MySQL的子查询