MySQL代码笔记3

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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值