下面的子查询将返回过去最近的日期,我想要调整它以便找到过去或将来的最近日期。
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
我已经阅读了ABS
和DATEDIFF
函数,但无法让我们按照我想象的方式工作:
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。
答案 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