和单表查询类似,根据不同的查询方式,分为子查询和连接查询,而子查询和连接查询根据表于表之间连接方式不同又有多种不同的查询方式
//先创建一个表 t_dept
create table t_dept(
_idint primarykey,
deptnoint(11),
dnamevarchar(20),
loc varchar(50));
insert into t_dept (_id,deptno,dname,loc) values ('1','10','ACCOUNTING','NEWYORK'),
('2','20','RESEARCH','DALLAS'),
('3','30','SALES','CHICAGO'),
('4','40','OPERATIONS','BOSTON');
mpno | ename | job | mgr | hiredate | sal | comm | deptno | _id | deptno | dname | loc |
7369 | SMITH | CLERK | 7902 | 2011-03-12 | 800 | null | 20 | 1 | 10 | ACCOUNTING | NEW YORK |
7369 | SMITH | CLERK | 7902 | 2011-03-12 | 800 | null | 20 | 2 | 20 | RESEARCH | DALLAS |
7369 | SMITH | CLERK | 7902 | 2011-03-12 | 800 | null | 20 | 3 | 30 | SALES | CHICAGO |
7369 | SMITH | CLERK | 7902 | 2011-03-12 | 800 | null | 20 | 4 | 40 | OPERATIONS | BOSTON |
7499 | ALLEN | SALESMAN | 7698 | 2012-03-12 | 1600 | 300 | 30 | 1 | 10 | ACCOUNTING | NEW YORK |
7499 | ALLEN | SALESMAN | 7698 | 2012-03-12 | 1600 | 300 | 30 | 2 | 20 | RESEARCH | DALLAS |
7499 | ALLEN | SALESMAN | 7698 | 2012-03-12 | 1600 | 300 | 30 | 3 | 30 | SALES | CHICAGO |
7499 | ALLEN | SALESMAN | 7698 | 2012-03-12 | 1600 | 300 | 30 | 4 | 40 | OPERATIONS | BOSTON |
select t1.ename,t1.job,t2.ename from t_employee t1, t_employee t2 where t1.mgr = t2.empno;
显示外连接
select t1.ename,t1.job,t2.enamefrom t_employee t1inner join t_employee t2 on t1.mgr = t2.empno;
selectt1.empno,t1.ename,t1.job,t2.dname,t2.loc
from t_employee t1
inner join t_dept t2 on t1. deptno =t2.deptno;
---------------------------------- or------------------------------------
select t1.empno,t1.ename,t1.sal,t1.job,t2.ename asmgr_name,t3.dname,t3.loc
from t_employee t1,t_employee t2,t_dept t3 where t1.mgr = t2.empno andt1.deptno = t3.deptno;
返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值。
select t1.ename,t1.job,t2.ename as mgr_name
from t_employee t1
left join t_employee t2 on t1.mgr = t2.empno;
ename | job | mgr_name |
SCOTT | ANALYST | JONES |
KING | PRESIDENT | null |
恰与左连接相反,返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。
selectt1.empno,t1.ename,t1.job,t2.dname,t2.loc
from t_employee t1
right join t_dept t2 on t1.deptno =t2.deptno;
empno | ename | job | dname | loc |
7900 | JAMES | CLERK | SALES | CHICAGO |
null | null | null | OPERATIONS | BOSTON |
select *
from t_employee t
where t.sal > (
select sal
from t_employee
where ename = 'SMITH');
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |