2016-12-05 139 views
1

我有兩個表,一個有入境日期,另一個有生效日期。我需要做的是選擇行的入口日期是最接近生效日期。我能找到的唯一資源是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嘗試,但它只是超時。

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

你想怎麼處理關係如果一個人1日在另1日起少? – xQbert

+1

輸入日期的方式輸入日期將始終在界面後 – user2168066

回答

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

如果入境日期總是比你可以使用有效日期越大以下

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 
        );