MySQL代码笔记3
子查询
–作为条件判断
select 列名 from 表名 where 条件(子查询结果)
查询结果作为外部查询的条件,子查询得到一行一列的结果才能作为外部查询的(不)等值判断条件。
–子查询作为枚举查询条件
select 列名 from 表名 where 列名 in(子查询结果)
select * from test where department_id in(select department_id from test where last_name=‘king’)
-工资高于60部门所有人的信息
%1.查询60部门所有人工资
select salary from test where department_id = 60;
%2.工资高于60部门所有人的信息(高于所有)
select * from test where salary>ALL(select salary from test where department_id = 60);
%3.工资高于60部门所有人的信息(高于部分)
select * from test where salary>ANY(select salary from test where department_id = 60);
–子查询作为一张表
select 列名 from (子查询的结果集) where 条件;
-查询员工表中工资排名前五位的员工信息
%思路:
%1.先对员工工资进行排序
select id,name,salary from test order by salary DESC;
%2. 选出前五名
select id,name,salary
from(select id,name,salary from test order by salary DESC)
as temp LIMIT 0,5;
注意:子查询作为临时表,为其赋予一个临时表名
合并查询(纵向拼接)
–合并两张表的结果(去除重复记录)
select * from t1 UNION select * from t2;
合并结果的两张表列数必须相同,列的数据类型可以不同
–合并两张表的结果(保留重复记录)
select * from t1 UNION ALL select * from t2;
表连接查询(表连接在一起后再查询)
语法:select 列名 from 表1 连接方式 表2 ON 连接条件
如果不指定条件会造成笛卡尔积的结果
–内连接查询(INNER JOIN … ON)
SQL标准:
select * from t1 INNER JOIN t2 ON t1.‘id’ = t2.‘id’;
MySQL标准:
select * from t1,t2 where t1.‘id’ = t2.‘id’;
–左外连接(LEFT JOIN …ON)
以左表为主表,依次向右匹配,若匹配不到返回NULL值
–右外连接(RIGHT JOIN …ON)