日期:2014-05-19  浏览次数:20558 次

两表关联取A表部分字段,B表最小数据及其他的字段优化
A
                  ID               姓名           工资           等级
1 张 300 1
2 王 400 2
3 唐 500 3

B
            等级_               工资_         备字1_         备字2_
1 400 SM               SDFF
2 420 SM2             FDDD
5 445 SMSD           SDF
6 460 SDD             GSDF

下面SQL如何优化,没经验,20分全送上了,
select   姓名,等级,工资,
新工资=(select     min(工资_)   from       b   where     等级 <等级_),
备字1     =(select   备字1_   from   b     where   工资_=   (
select     min(工资_)   from       a     where     等级 <等级_)       )
备字2     =(...取法同上)
  from     a

------解决方案--------------------
select 姓名,等级,工资,工资,字1,备注2
from a
,b c
where not exists(select 1 from b where 等级_> =等级_ or 工资_> =c.工资_)
------解决方案--------------------
create table A(ID int, 姓名 varchar(10), 工资 int, 等级 int)
insert A select 1, '张 ',300,1
union all select 2, '王 ',400,2
union all select 3, '唐 ',500,3

create table B(等级_ int, 工资_ int, 备字1_ varchar(10), 备字2_ varchar(10))
insert B select 1,400, 'SM ', 'SDFF '
union all select 2,420, 'SM2 ', 'FDDD '
union all select 5,445, 'SMSD ', 'SDF '
union all select 6,460, 'SDD ', 'GSDF '

select 姓名, 工资, 等级,
新工资=(select min(工资_) from B where tmp.等级 <等级_),
备字1=( select 备字1_ from B where 工资_=(select min(工资_) from B where tmp.等级 <等级_) ),
备字2=( select 备字2_ from B where 工资_=(select min(工资_) from B where tmp.等级 <等级_) )
from A as tmp

--result
姓名 工资 等级 新工资 备字1 备字2
---------- ----------- ----------- ----------- ---------- ----------
张 300 1 420 SM2 FDDD
王 400 2 445 SMSD SDF
唐 500 3 445 SMSD SDF

(3 row(s) affected)


我的异常网推荐解决方案:软件开发者薪资,http://www.aiyiweb.com/other/1391128.html