在另一个表中选择最接近日期的日期

时间:2016-12-05 19:32:05

标签: mysql

我有两个表,一个有进入日期,另一个有生效日期。我需要做的是选择入口日期最接近生效日期的行。我能找到的唯一资源是row_number(),它在MySQL中似乎不起作用。

数据

             Table A              Table B
           id    effdate         id    Aid    entrydate
           1     2015-10-19      1     1       2015-12-17
                                 2     1       2015-12-18
                                 3     1       2015-12-20

我要做的是选择

id    effdate      entrydate
1     2015-10-19   2015-12-17

到目前为止,我已尝试在entrydate上使用min(),但它只会超时。

SELECT a.id, a.effdate, b.entrydate
FROM tableA a
JOIN tableB b on a.id = b.Aid

2 个答案:

答案 0 :(得分:1)

SELECT a.id, a.effdate, b.entrydate
FROM tableA a
JOIN tableB b on a.id = b.Aid
ORDER BY DATEDIFF(entrydate, effdate) ASC
         -- you might want to order here by additional fields to break the ties
LIMIT 1;

答案 1 :(得分:1)

如果输入日期始终大于生效日期,您可以使用以下

select a.id, a.effdate, b.entrydate from aa a, bb b
where a.id = b.aid 
  and b.entrydate = (select Min(bi.entrydate) 
                     from bb bi 
                     where bi.id = a.id
                    );
相关问题