mysql在两个带日期的表之间找到最低值

时间:2013-02-07 20:48:47

标签: mysql

我有两个表tb1和tb2

tb1
-----
tb1Id

tb2
-----
tb2Id | tb1Id | dateTB2Submitted | timeIn

当我加入tb1时,如何找到各行的最低日期。例如:

SELECT tb1.tb1id, 
       tb2.datetb2submitted, 
       tb2.timein 
FROM   tb1, 
       tb2 
WHERE  tb1.tb1id = tb2.tb1id 

+-------------+----------------------+----------+
| tb1.tb1Id   | tb2.dateTB2Submitted | timeIn   |
+-------------+----------------------+----------+
|           1 | 2011-04-02           | 11:00:00     
|           1 | 2011-04-02           | 10:30:00      <--i want this
|           2 | 2011-04-29           | 12:30:00     
|           2 | 2011-04-29           | 10:30:00      <--i want this

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT tb1.tb1id, 
       tb2.datetb2submitted, 
       Min(tb2.timein) AS timeIn 
FROM   tb1 
       INNER JOIN tb2 
               ON tb1.tb1id = tb2.tb1id 
GROUP  BY tb1.tb1id, 
          tb2.datetb2submitted 

答案 1 :(得分:0)

试试这个

SELECT tb2.tb2id, tb2.tb1id, tb2.datetb2submitted, Min(tb2.timein) AS timeIn
FROM tb2 JOIN 
(
  SELECT tb1.tb1id, MIN(tb2.datetb2submitted) AS datetb2submitted
  FROM tb1 INNER JOIN tb2 ON tb1.tb1id = tb2.tb1id
  GROUP  BY tb1.tb1id
) AS lowestdate 
ON lowestdate.tb1id = tb2.tb1id AND lowestdate.datetb2submitted = tb2.datetb2submitted
GROUP BY tb2.tb1id
;