寻找更好的Sql查询

时间:2016-09-24 10:46:42

标签: sql-server-2008 tsql

我需要使用表@tblData LastDateTimeMAX ChildDateTime = 1更新@tblChildData表的IsLast列。

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

2 个答案:

答案 0 :(得分:0)

您可以尝试这样更新:

UPDATE t
SET t.lastDateTime = (SELECT
  MAX(childDatetime)
FROM @tblChildData
WHERE did = t.did
AND IsLast = 1)
FROM @tblData t

不确定为什么你在下面再次加入了childdata。检查输出与您的预期输出。显然它会表现得更好,因为它没有第二次加入其他表。以下是您的查询之间的执行计划比较

我的更新脚本<​​/ p>

enter image description here

您的更新脚本<​​/ p>

enter image description here

答案 1 :(得分:0)

你可以尝试这个

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