mysql用法之多表查询

内连接:把两张表相同的地方查询出来 inner join

左连接:包括内连接,同时还查询左表特有的内容

右连接:包括内连接,同时还查询右表特有的内容

id 为关联字段

内连接

关键:找到两张表关联的字段

select * from table1 inner join table2 on table1.字段 = table2.字段

下面是通过 studentNO 这个字段相关联

隐式内连接

查询指定的字段

where写法

inner写法

起别名 as可省略

下面介绍将用到的表的相关信息

可以看出其关联字段

联合查询结果

写这种sql语句的方法

1.先连起来

2.关联关系搞清楚

3.进一步进行筛选where

多表查询

sql: 搭框架

多表 先联合

where 具体条件

看到底需要什么字段

oreder by limt 联合使用

左连接

left join

查询所有学生的信息以及成绩,包括没有成绩的学生

右连接

right join

查询所有课程的信息,包括没有成绩的课程

多表联合查询,同名字段的处理方式

如果一条select要用到多个表,表中有同名字段,需要表名.字段加以区分

否则会报错: 

自关联

同时记录省 市 aera

省没有所属 pid为null

可以帮助简化表结构:

自关联是同一张表做连接查询

自关联下一定找到同一张表可关联的不同字段

找到广东省下面的市

子查询

查询大于平均年龄的学生信息:

标量子查询:子查询返回结果只有一行,一列

子查询:显示的字段与主查询相关的

列子查询:子查询结果返回一列,多行

查询所有女生的信息和成绩:

表级子查询 子查询返回多行多列

练习:

表的基本信息 找到表关联关系

select count(*) from employees where sex = '男';//8
select count(*) from employees where sex = '女';//5
select sex,count(*) from employees group by sex;

select count(*) from employees where politicalstatus != '党员';//8

select employees.empid, employees.empname,departments.deptname from employees inner join departments on employees.deptid = departments.deptid;

select employees.empid, employees.empname,salary.salary from employees inner join salary on employees.empid = salary.empid;

select e.empid, e.empname,departments.deptname from 
(select * from employees where leader is null ) e 
inner join departments on e.deptid = departments.deptid;

select deptid, count(*) from employees group by deptid having count(*) > 4;

select deptname,deptid from departments where deptid in 
(select deptid from employees group by deptid having count(*) > 4);

select empid,empname from employees where deptid in
(select deptid from departments where deptname in ('开发部','测试部'));

select empname,politicalstatus from employees where deptid in
(select deptid from departments where deptname = '市场部')
and sex = '女';//孙尚香

select employees.empname,salary.salary from employees left join salary on employees.empid = salary.empid;//周瑜无工资

select sum(salary.salary) from 
(select * from employees where empname not like '孙%') ee 
inner join salary on ee.empid = salary.empid;//29899

内连接 inner join

左连接 left join

右连接 right join

隐式连接(where)

自关联:同一张表的字段不同

子查询:

标量子查询(一行一列)在主查询的条件中一般用比较运算符

列子查询 (一列多行 ) 在主查询的条件中一般用in

表子查询(多行多列) 表级子查询返回结果就是一张表 一般用于和其他表做联合查询

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值