Sql server 2008 寻找更好的Sql查询
我需要使用表Sql server 2008 寻找更好的Sql查询,sql-server-2008,tsql,Sql Server 2008,Tsql,我需要使用表@tblchildata的MAX ChildDateTime和IsLast=1更新@tblData表的LastDateTime列 Declare @tblData Table(DId Int, TypeId Int, LastDateTime DateTime) Insert Into @tblData Values(1, 1, Null), (2, 2, Null), (3, 2, Null) Declare @tblChildData Table(CId Int, DId In
@tblchildata
的MAX ChildDateTime
和IsLast
=1更新@tblData
表的LastDateTime
列
Declare @tblData Table(DId Int, TypeId Int, LastDateTime DateTime)
Insert Into @tblData Values(1, 1, Null), (2, 2, Null), (3, 2, Null)
Declare @tblChildData Table(CId Int, DId Int, ChildDateTime DateTime, IsLast Bit)
Insert Into @tblChildData Values (10, 1, '2016-09-20 07:47:03.000', Null)
, (11, 2, '2016-09-20 08:47:03.000', Null)
, (12, 2, '2016-09-20 09:32:03.000', 1)
, (13, 2, '2016-09-20 10:47:03.000', Null)
, (14, 2, '2016-09-20 11:32:03.000', 1)
, (15, 1, '2016-09-20 06:47:03.000', Null)
我能够更新以下查询,但寻找更好的查询。谢谢
UPDATE UQ
SET UQ.LastDateTime = (
SELECT MAX(D.ChildDateTime)
FROM @tblData C
JOIN @tblChildData D ON C.DId = D.DId
AND C.TypeId = 2
AND D.IsLast = 1
)
FROM @tblData UQ
JOIN @tblChildData PD ON UQ.DId = PD.DId
AND UQ.TypeId = 2
AND PD.IsLast = 1
SELECT * FROM @tblData
您可以尝试如下更新:
UPDATE t
SET t.lastDateTime = (SELECT
MAX(childDatetime)
FROM @tblChildData
WHERE did = t.did
AND IsLast = 1)
FROM @tblData t
不确定您为什么在下面再次加入childdata。检查输出与预期输出。显然,它的性能会更好,因为它不会再次加入另一个表。下面是您的查询与执行计划之间的比较
我的更新脚本
您的更新脚本
您可以尝试如下更新:
UPDATE t
SET t.lastDateTime = (SELECT
MAX(childDatetime)
FROM @tblChildData
WHERE did = t.did
AND IsLast = 1)
FROM @tblData t
不确定您为什么在下面再次加入childdata。检查输出与预期输出。显然,它的性能会更好,因为它不会再次加入另一个表。下面是您的查询与执行计划之间的比较
我的更新脚本
您的更新脚本
你可以试试这个
UPDATE UQ SET UQ.LastDateTime = (
SELECT MAX(D.ChildDateTime)
FROM @tblChildData D where D.DId=UQ.DId
AND UQ.TypeId = 2
AND D.IsLast = 1) FROM @tblData UQ where UQ.TypeId = 2
你可以试试这个
UPDATE UQ SET UQ.LastDateTime = (
SELECT MAX(D.ChildDateTime)
FROM @tblChildData D where D.DId=UQ.DId
AND UQ.TypeId = 2
AND D.IsLast = 1) FROM @tblData UQ where UQ.TypeId = 2
谢谢你更好的编辑谢谢你更好的编辑