MySQL查询语句(select)详解(2)

7.子查询

当进行查询的时候,需要的条件另外一个select语句的结果,这时候就要用到子查询

用于子查询的主要关键字有:in,not in,=,!=,exists,not exists等。

以下两张表学生表爱好表

 

 

[student表]中查出爱好在[hobby表]中的学生
select*from student where hobby in (select hobby from hobby);

 

如果子查询只有1条记录,可以用=代替in
select*from student where hobby = (select hobby from hobby limit 1);

 

子查询语法上可以用表连接进行替代

子查询:
select*from student where hobby in (select hobby from hobby);
用表连接进行替代
select student.* from student,hobby where student.hobby = hobby.hobby;

结果都是相同的:

表连接替代子查询的意义:

1.MySQL4.1以前的版本不支持子查询,需要用表连接来实现子查询的内容

2.表连接在很多情况下用于优化子查询

 

8.记录联合

记录联合可以把两个或多个select查询的结果合并一起显示出来。

select * from t1 union/union all  select * from t2...union/union allselect * from tn;

union 和 union all的区别是union all是把结果集直接合并在一起,而union会将union后的结果进行一次distinct去重。

 

posted @ 2016-11-28 20:50  drake-guo  阅读(3668)  评论(0编辑  收藏  举报