考虑这张表:
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;