Mysql exists subquery bitsCN.com
Mysql exists subquery
Subqueries can be divided into: from where and exists subqueries
Category table:
[SQL]
Mysql> select * from category;
+ ---- + --------- +
| Id | c_name |
+ ---- + --------- +
| 1 | ios |
| 2 | android |
| 3 | sb |
+ ---- + --------- +
3 rows in set
Item table:
[SQL]
Mysql> select * from goods;
+ ---- + --------- + -------- + ------- + ----- +
| Id | name | cat_id | price | num |
+ ---- + --------- + -------- + ------- + ----- +
| 1 | Apple | 1 | 4999 | 2 |
| 1 | nexus4 | 2 | 1999 | 3 |
| 4 | glory 2 | 2 | 1888 | 5 |
| 6 | Samsung | 2 | 3000 | 2 |
+ ---- + --------- + -------- + ------- + ----- +
6 rows in se
Requirement: only identify the categories of products under the category
[SQL]
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
BitsCN.com