隐式内连接
select * from book , sell where book.图书编号 = sell.图书编号;
可以给表起别名,如果起了表别名就不能使用原表名查询数据了
select * from book b , sell s where b.图书编号 = s.图书编号;
显式内连接
select * from book join sell on sell.图书编号 = book.图书编号;
左外连接(完全包含左表的数据,和相应的右表选取字段的信息,不会填充Null值)
select book.书名 , sell.订单号 from book left join sell on sell.图书编号 = book.图书编号;
右外连接(完全包含右表的数据,和相应的左表选取字段的信息,不会填充Null值)
select book.书名 , sell.订单号 from sell right join book on sell.图书编号 = book.图书编号;
自连接 (必须起别名才能自连接)
select a.name '领导' , b.name '员工' from emp a , emp b where a.managerid = b.workerid;
联合查询
将两次查询的结果合并,不去重
select * from sell where 订购册数>5
union all
select * from sell where 订购单价>20 ;
将两次查询的结果合并,且去重
select * from sell where 订购册数>5
union
select * from sell where 订购单价>20 ;
标量子查询
查询班级编号为会计13-1班的学生信息
select * from student where 班级编号 = (select 班级编号 from class where 班级名称 = '会计13-1班');
列子查询
// in 查询指定集合范围的数据(这里是查询研发部和财务部的员工信息)
select * from emp where emp.dept_id in (select id from dept where name = '研发部' or name = '财务部');
// not in 查询不包含指定集合范围的数据
select * from emp where emp.dept_id not in (select id from dept where name = '研发部' or name = '财务部');
// any 以子查询作为查询条件,子查询中有满足的条件数值即可
select * from employee where age > any(select age from employee where age>=20);
// some 以子查询作为查询条件,查询员工表中年龄等于子查询条件(年龄大于等于20岁)的信息 与 any 一样
select * from employee where age = some(select age from employee where age>=20);
// all 以子查询作为查询条件,查询比研发部所有员工年龄都大的其他部门员工信息
select * from emp where age > all(select age from emp where dept_id = (select id from dept where name = '研发部'));
行子查询
// 查询工作和工资与金庸一样的员工信息
select * from emp where (job,salary) = (select job , salary from emp where name = '金庸');
// 查询工作与工资一样的员工信息,和行子查询效果一样
select * from emp where job = '开发' or salary = 8400 ;
表子查询(返回的结果多行多列)
// 查询工作和工资与金庸和杨逍一样的员工信息
select * from emp where (job,salary) in (select job , salary from emp where name = '金庸' or name = '杨逍');
// 查询入职日期是'2001-01-01'之后的员工信息
select * from emp where entrydate > '2001-01-01';
// 查询入职日期是'2001-01-01'之后的员工信息,及其部门信息(将子查询作为一张表进行查询)
select * from (select * from emp where entrydate > '2001-01-01') e left join dept on e.dept_id = dept.id;
MySQL多表查询操作
于 2024-04-30 11:27:08 首次发布