日期:2014-05-18  浏览次数:20445 次

UPDATE的问题,高手速度来指点哈
UPDATE 表A set z=b.b1 where x as b on a.id = b.id and a.type = b.type

问题:
x表 
id type
1 1
2 1
3 1

表A
z type
0 1


需要更新成
表A
z type
3 1


------解决方案--------------------
SQL code
UPDATE 表A SET 表A.Z=X.id
FROM   表A 
INNER  JOIN (SELECT type,MAX(id) AS id FROM X GROUP BY type) AS X
       ON 表A.type=X.type

------解决方案--------------------
UPDATE 表A SET 表A.Z=X.id
FROM 表A 
INNER JOIN (SELECT type,MAX(id) AS id FROM X GROUP BY type) AS X
ON 表A.type=X.type
------解决方案--------------------
SQL code

create table tabx
(id int, type int)

insert into tabx
select 1, 1 union all
select 2, 1 union all
select 3, 1

create table taba
(z int, type int)

insert into taba
select 0, 1


update a 
set a.z=b.maxid
from taba a
inner join
(select type,max(id) maxid
from tabx group by type) b
on a.type=b.type

select * from taba

z           type
----------- -----------
3           1

(1 row(s) affected)

------解决方案--------------------
SQL code

create table tabx
(id int, type int, time datetime, filepath int)

insert into tabx 
select 1, 1, '2011-01-01 14:00:00', 1 union all
select 2, 1, '2011-01-01 17:00:00', 2 union all
select 3, 1, '2011-01-01 12:00:00', 3

create table taba
(z int, type int, time datetime, filepath int)

insert into taba(z,type)
select 0, 1


update a 
set a.z=b.id,
    a.time=b.time,
    a.filepath=b.filepath
from taba a
inner join tabx b
on a.type=b.type
where b.time=
(select max(time) from tabx c 
 where c.type=b.type)

select * from taba

z           type        time                    filepath
----------- ----------- ----------------------- -----------
2           1           2011-01-01 17:00:00.000 2

(1 row(s) affected)