子查询可以分为:from where 和exists子查询
分类表:
mysql> select * from category;
+----+---------+
| id | c_name |
+----+---------+
| 1 | ios |
| 2 | android |
| 3 | sb |
+----+---------+
3 rows in set
mysql> select * from goods;
+----+---------+--------+-------+-----+
| id | name | cat_id | price | num |
+----+---------+--------+-------+-----+
| 1 | 苹果 | 1 | 4999 | 2 |
| 2 | nexus4 | 2 | 1999 | 3 |
| 4 | 荣耀2 | 2 | 1888 | 5 |
| 6 | 三星 | 2 | 3000 | 2 |
+----+---------+--------+-------+-----+
6 rows in se
要求:只找出分类下有商品的分类
mysql> select * from category c where exists (select * from goods where cat_id=c.id);
+----+---------+
| id | c_name |
+----+---------+
| 1 | ios |
| 2 | android |
+----+---------+
2 rows in set
本文通过一个具体的MySQL查询案例介绍了如何利用exists子查询来筛选出那些在商品表中有对应记录的分类。通过这种方式,我们可以高效地找到所有拥有至少一件商品的分类。
3849

被折叠的 条评论
为什么被折叠?



