2

我正在寻找通过平均该行之前和之后最近的 id 的日期来更新该date列所在的行。NULL

在下面的数据中,它会将 ID 行更新262011-10-19

什么 MySQL 语句会完成这个?


补充说明:

数据看起来像这样:

id     date           title
--------------------------------------------
12     2011-09-01     Example One
23     2011-10-02     Example Two
26     NULL           Example Three
27     2011-11-05     Example Four
29     2012-01-05     Example Five
37     NULL           Example Six
38     2012-02-03     Example Seven
--------------------------------------------

我宁愿不使用程序。

到目前为止,我已经...

UPDATE `table`
    SET `date`=
         (AVG(
              (SELECT `date` FROM `table` WHERE `id`< ID_OF_PARENT_QUERY AND `date` IS NOT NULL LIMIT 1),
              (SELECT `date` FROM `table` WHERE `id`> ID_OF_PARENT_QUERY AND `date` IS NOT NULL LIMIT 1)
         ))

    WHERE `date` IS NULL
4

1 回答 1

4
UPDATE tableX AS t
  JOIN tableX AS next
    ON next.id =
       ( SELECT MIN(n.id)
         FROM tableX AS n
         WHERE n.id > t.id
           AND n.dateX IS NOT NULL
       )
  JOIN tableX AS prev 
    ON prev.id =
       ( SELECT MAX(p.id)
         FROM tableX AS p
         WHERE p.id < t.id
           AND p.dateX IS NOT NULL
       )
SET t.dateX = prev.dateX + INTERVAL (DATEDIFF(next.dateX, prev.dateX) / 2) DAY
WHERE t.dateX IS NULL
于 2012-04-09T06:28:49.277 回答