MySQL:查找过去或将来的最近日期

时间:2014-05-14 18:59:29

标签: mysql sql subquery datediff

下面的子查询将返回过去最近的日期,我想要调整它以便找到过去或将来的最近日期。

SELECT date,

    (SELECT value
     FROM `users check-ins` as c
     WHERE c.date < p.date AND `userid` = '$userid'
     ORDER BY c.date DESC
     LIMIT 1) as weight

FROM `users photos` as p
WHERE `userid` = '$userid'
ORDER BY date ASC

我已经阅读了ABSDATEDIFF函数,但无法让我们按照我想象的方式工作:

SELECT date,

    (SELECT value
     FROM `users check-ins` as c
     WHERE `userid` = '$userid'
     ORDER BY ABS(DATEDIFF(c.date, p.date)) DESC
     LIMIT 1) as weight

FROM `users photos` as p
WHERE `userid` = '$userid'
ORDER BY DATE ASC

因此子查询应该从最接近value的行返回p.date

修改

这里是SQLfiddle

1 个答案:

答案 0 :(得分:0)

您需要在子查询中按asc而不是desc订购:

SELECT date,

    (SELECT value
     FROM `users check-ins` as c
     WHERE `userid` = '$userid'
     ORDER BY ABS(DATEDIFF(c.date, p.date)) ASC
     LIMIT 1) as weight

FROM `users photos` as p
WHERE `userid` = '$userid'
ORDER BY DATE ASC