我知道可能有问题是this的副本,但当我尝试他们提供的答案时,我得到了不同的答案......
所以我有一张桌子,今天是06/02/2017
的 tblpres
patID pres presDate
1 | asd | 05/29/2017
2 | qwe | 05/20/2017
3 | zxc | 06/01/2017
4 | ety | 05/27/2017
5 | ttt | 05/18/2017
所以我做了一个查询,以获得最接近当前日期的日期,但我得到id 3 whch是最接近当前日期的日期我得到差异答案..
SELECT pres,presDate
FROM tblpres
WHERE patID = '20150518384'
ORDER BY presDate DESC
LIMIT 1
SELECT pres, presDate
FROM tblpres
WHERE patID = '20150518384'
ORDER BY ABS( DATEDIFF(presDate, `06/02/2017` ) )
LIMIT 1
SELECT pres, presDate
from tblpres
WHERE patID = '20150518384'
order by abs('06/02/2017' - presDate) desc
limit 1
SELECT pres,presDate
FROM tblpres
WHERE `patID` = '20150518384' AND presDate < '06/02/2017'
ORDER BY presDate
LIMIT 1
这是我试过的查询,但似乎没有任何工作......我确实得到了这个查询的答案,但结果不是我所期待的..
答案 0 :(得分:1)
使用ISO / ANSI标准日期格式:
SELECT pres, presDate
FROM tblpres
WHERE patID = '20150518384'
ORDER BY ABS( DATEDIFF(presDate, '2017-06-02') )
LIMIT 1;
或者,更好的是,使用CURDATE()
:
SELECT pres, presDate
FROM tblpres
WHERE patID = '20150518384'
ORDER BY ABS( DATEDIFF(presDate, CURDATE()) )
LIMIT 1;
如果presdate
实际上不是日期,您可能需要将其转换为:
SELECT pres, presDate
FROM tblpres
WHERE patID = '20150518384'
ORDER BY ABS( DATEDIFF(str_to_date(presDate, '%m/%d/%Y'), CURDATE()) )
LIMIT 1;