MySQL连接查询

使用背景:学生表(student)、课程表(course)、考试表exam

 SQL内连接(inner join)

select a.uid,a.name,a.age,a.sex,b.cid,b.cname,b.credit,c.score
from exam c
inner join student a on c.uid=a.uid
inner join course b on c.cid=b.cid
where c.uid=1 and c.cid=2;

<1>区分大表和小表,按照数据量来区分,小表永远是整表扫描,然后去大表搜索,一般在大表中创建索引。例:从exam大表中取出所有的c.uid和c.cid,然后拿着这些uid和cid去student和course小表中搜索

<2>可结合分组、排序操作,进行更精确的搜索

<3>先执行on连接产生临时表,再执行where在临时表中筛选符合条件的数据

结合limit分页优化SQL语句

select a.id,a.email,a.passward from t_user a inner join(select id from t_user limit 150000,10) b on a.id=b.id;

在()中创建一个临时表作为小表,提升SQL效率

SQL外连接(outer join)

SQL左连接查询(left join)

SELECT a.属性名列表,b.属性名列表 FROM table_name1 a LEFT JOIN table_name2 b on a.id=b.id;

//把left这边的表所有数据显示出来,在右表中不存在相应数据,则显示NULL
select a.*,b.* from student a left outer join exam b on a.uid=b.uid; 

SQL右连接查询(right join)

//把right这边的表所有数据显示出来,在左表中不存在相应数据,则显示NULL
select a.*,b.* from student a right outer join exam b on a.uid=b.uid; 

实际应用场景:查询在当前连接中为空的属性

select a.* from student a left join exam b on a.uid=b.uid where b.cid is null;

//not in 对于索引的命中并不高,推荐使用外连接
select * from student where uid not in (select distinct uid from exam);

内连接和外连接的区别:

<1>对于inner join内连接,过滤条件写在where的后面和on连接条件里面,效果是一样的。

对于outer join外连接,在判断null和限制条件的情况下,限制条件写在on里面,where条件过滤只判断null的情况

select a.* from student a left join exam b on a.uid=b.uid and b.cid=3 where b.cid is null;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值