子查询转化为连接查询的例子
Sql代码 use mytest; drop table if exists jobs; CREATE TABLE jobs( employee varchar(30), title varchar(30) ); drop table if exists ranks; CREATE TABLE ranks( title varchar(30), rank varchar(30) ); drop table if exists salary; CREATE TABLE salary( rank varchar(30), payment int(11) ); insert into jobs values('张三','经理'),('李四','总经理'),('王五','总经理助理'); insert into ranks values('经理','三'),('总经理','一'),('总经理助理','二'); insert into salary values('一',20000),('二',8000),('三',7000),('四',7000); use mytest;drop table if exists jobs;CREATE TABLE jobs(employee varchar(30),title varchar(30));drop table if exists ranks;CREATE TABLE ranks(title varchar(30),rank varchar(30));drop table if exists salary;CREATE TABLE salary(rank varchar(30),payment int(11));insert into jobs values('张三','经理'),('李四','总经理'),('王五','总经理助理');insert into ranks values('经理','三'),('总经理','一'),('总经理助理','二');insert into salary values('一',20000),('二',8000),('三',7000),('四',7000);
建立了三个表,分别是jobs员工工作表,记录了员工的工作,第二表ranks是岗位等级表,记录每一个工作岗位的等级,第三个表slary自然就是HR为每一个等级的定的薪资标准了。
现在要知道张三的工资是多少,就需要使用三张表才能得到数据,
使用子查询的方法如下:
Sql代码 select payment from salary where rank=( SELECT rank from ranks where title=( SELECT title from jobs where employee='张三') ); select payment from salary where rank=(SELECT rank from ranks where title=(SELECT title from jobs where employee='张三'));
Sql代码 select payment from salary s,ranks r,jobs j where j.employee='张三' and j.title = r.title and s.rank = r.rank; select payment from salary s,ranks r,jobs j where j.employee='张三' and j.title = r.title and s.rank = r.rank;
Java代码 select salary.rank from salary where rank not in(select rank from ranks); select salary.rank from salary where rank not in(select rank from ranks);
Sql代码 select salary.rank from salary left join ranks on salary.rank=ranks.rank where ranks.rank is null; select salary.rank from salary left join ranks on salary.rank=ranks.rank where ranks.rank is null;
Sql代码 DROP TABLE if exists orders; create table orders( customer varchar(30), whn date, totalitems int(11) ); insert into orders values('jj','2010-10-10',5), ('jj','2010-10-11',3), ('jj','2010-10-12',1), ('aa','2010-10-10',5), ('bb','2010-10-10',8), ('cc','2010-10-10',10); DROP TABLE if exists orders;create table orders(customer varchar(30),whn date,totalitems int(11));insert into orders values('jj','2010-10-10',5),('jj','2010-10-11',3),('jj','2010-10-12',1),('aa','2010-10-10',5),('bb','2010-10-10',8),('cc','2010-10-10',10);Sql代码 select customer,whn,totalitems from orders o1 where o1.totalitems=( SELECT max(totalitems) from orders o2 where o1.customer = o2.customer ); select customer,whn,totalitems from orders o1 where o1.totalitems=(SELECT max(totalitems) from orders o2 where o1.customer = o2.customer);
Sql代码 select o1.* from orders o1 join orders o2 on(o1.customer=o2.customer) group by o1.customer having o1.totalitems=max(o2.totalitems ); select o1.* from orders o1 join orders o2 on(o1.customer=o2.customer) group by o1.customer having o1.totalitems=max(o2.totalitems);