博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql多表查询
阅读量:5888 次
发布时间:2019-06-19

本文共 1538 字,大约阅读时间需要 5 分钟。

多表查询,SQL JOINS

1. inner join内连接

select s.name as student_name,t.name as teacher_name from students as s inner join teachers as t on s.teacherid=t.tid; /*2张表取交集,内连接*/

2. 交叉连接

select * from students cross join teachers; /*笛卡尔乘积,students表内容和teacher表内容各自组合一遍*/

 

3. 左外连接

select s.name as student_name,t.name as teacher_name from students as s left outer join teachers as t on s.teacherid=t.tid;

 

1.)左内连接

select s.name as student_name,t.name as teacher_name from students as s left outer join teachers as t on s.teacherid=t.tid and t.name is null;

 

4.右外连接

select s.name as student_name,t.name as teacher_name from teachers as t right outer join students as s on s.teacherid=t.tid;

 

5.完全外连接

union

 

 

MariaDB [hellodb]> select s.name as student_name,t.name as teacher_name from students as s left outer join teachers as t on s.teacherid=t.tid

-> union

-> select s.name as student_name,t.name as teacher_name from students as s right outer join teachers as t on s.teacherid=t.tid;

 

5.自连接

select s1.name as emp, s2.name as leader from students as s1 inner join students as s2 on s1.teacherid=s2.stuid; /*使用内连接取2张表的交集*/

 

select s1.name as emp, s2.name as leader from students as s1 left outer join students as s2 on s1.teacherid=s2.stuid; /*使用左外连接取2张表的交集*/

 

6.子查询

#查看分数大于平均分的分数

select stuid,score from scores where score > (select avg(score) from scores);

 

#查询分数大于平均分数,学生的姓名和分数

select st.name,sc.score from students as st inner join scores as sc on st.stuid=sc.stuid and score > (select avg(score) from scores);

 

 

转载于:https://www.cnblogs.com/ifelz/p/9159826.html

你可能感兴趣的文章
我的友情链接
查看>>
XSS测试平台
查看>>
我的友情链接
查看>>
android 进程
查看>>
ceph-deploy源码分析(一)——源码结构与cli <转>
查看>>
Swift 对象内存模型探究(一)
查看>>
Spring集成JPA后,报“Not an managed type: class x.x.x"
查看>>
sublime配置全攻略【转】
查看>>
我的友情链接
查看>>
Inxi:获取Linux的系统和硬件信息
查看>>
pop3:Mailbox isn't a valid mbox file报错解决办法:
查看>>
nfs 原理详解
查看>>
现在的教育:感慨之二
查看>>
图解IntelliJ IDEA v13应用服务器的运行配置
查看>>
zabbix 监控目录大小
查看>>
Linux Shell从入门到删除根目录跑路指南
查看>>
深入了解MyBatis参数
查看>>
FreeBSD中安装源的方法
查看>>
浮动层代码
查看>>
1.安装zabbix server
查看>>