如何将表中的值更新为其他行的MAX?

时间:2013-07-30 16:37:55

标签: sql sql-server

考虑下表:

Declare @Content table (id int, ParentId int, CreatedOn DateTime, LastCommentOn DateTime)

insert into @Content values 
(1, null, GETDATE() - 10, '2001-12-01'),
(2, 1, GETDATE() - 9, GETDATE() - 8),
(3, 1, GETDATE() - 8, GETDATE() - 7),
(4, 1, GETDATE() - 7, GETDATE() - 6),
(5, null, GETDATE() - 6, '2001-12-01'),
(6, 5, GETDATE() - 5, GETDATE() - 4),
(7, 5, GETDATE() - 4, GETDATE() - 3),
(8, null, GETDATE() - 3, '2001-12-01'),
(9, 8, GETDATE() - 2, GETDATE() - 1)

我想将所有主要内容(由ParentId标识为null)更新为该内容的最后一条评论的CreatedOn日期。

我试过

update @Content m 
set LastCommentOn = MAX(select CreatedOn from @Content c where c.ParentId = m.Id) 
where ParentId is null and LastCommentOn = '2001-12-01'

update @Content 
set LastCommentOn = MAX(select CreatedOn from @Content c where c.ParentId = m.Id) 
from @Content m
where ParentId is null and LastCommentOn = '2001-12-01'

但是我无法做到我想做的事情。

我如何在MSSQL中执行此操作?

(另外,mysql上的查询是一样的吗?)


接受的答案在MS SQL上运行得很好,但是,在MySql上,我找不到在一个语句中执行此操作的方法,我不得不将查询拆分为两部分并更新..所以这是有用的我在mysql上

SET SQL_SAFE_UPDATES=0;

Create temporary table tmpContentDates 

select Max(ParentId) as pid, Max(CreatedOn) as pd
From Content
where ParentId is not null
Group By ParentId; 

update Content as c
    inner join tmpContentDates d on c.Id = d.pid
set c.LastCommentedOn = d.pd
where ParentId is null
    and LastCommentedOn = '2001-12-01';

drop table tmpContentDates;

3 个答案:

答案 0 :(得分:2)

你试过吗?

update @Content 
set LastCommentOn =  
(select MAX(CreatedOn) from @Content c where c.ParentId = m.Id) 
from @Content m
where ParentId is null and LastCommentOn = '2001-12-01'

答案 1 :(得分:1)

你的SQL应该是

update @Content m 
set LastCommentOn = (select MAX(CreatedOn) from @Content c where c.ParentId = m.Id)
where ParentId is null and LastCommentOn = '2001-12-01'

假设max适用于DateTime

答案 2 :(得分:1)

update @Content 
set LastCommentOn = MAX(c.CreatedOn) 
from @Content m
inner join @Content c on c.ParentId = m.Id
where ParentId is null and LastCommentOn = '2001-12-01'