# 子查询

# 1、作为普通逻辑表的子查询

select m.user_code from (select user_code,user_name from `user`) m limit 10

上面的sql语句from后面紧跟"() m" 这个括号内的就是子查询,括号后面的m就是声明这个子查询的一个别名,在外层的主查询中m可以作为表名来使用

# 2、作为逻辑字段的子查询

select (select car_name from user_car where user_car.user_code=`user`.user_code) as carName from `user` where user_name="小明"

上面的sql语句,把子句"select car_name from user_car where user_car.user_code=user.user_code"的查询结果返回作为汽车名称。

**最终语义:**用户名称为小明的人的汽车名称

# 3、作为条件的子查询

select car_name from user_car where user_code in (select user_code from `user` where user_name="小明")

上面的sql语句,把子句"select user_code from user where user_name="小明""的查询结果作为条件用在主句中。

**最终语义:**用户名称为小明的人的汽车名称

# 4、连表的子查询 - join

select user_car.car_name from user_car inner join (select user_code from `user` where user_name="小明") m on m.user_code=user_car.user_code

上面的sql语句,把子句"select user_code from user where user_name="小明""的查询结果作为一个逻辑意义上的表m和user_car表进行连接。

最终语义: 用户名称为小明的人的汽车名称

在各种join/union连接中各个表的位置都是可以用子查询结果作为逻辑表链接的。

2、作为字段的子查询3、作为条件的子查询4、连表的子查询 - join的例子中的最终语义都是相同的,但是写法不同,都用了查询子句