从几张表中获取最早的日期

时间:2015-03-29 16:53:59

标签: mysql sql

我有3个带有时间戳列的表。我想写一个查询来找出哪个是最早的数据点(忽略任何空值)。这是我目前的查询:

SELECT gps.time,
       cadence.added_on,
       `heart-rate`.added_on
FROM   gps
       JOIN cadence
         ON cadence.rider_id = gps.rider_id
       JOIN `heart-rate`
         ON `heart-rate`.rider_id = gps.rider_id
ORDER  BY gps.time,
          cadence.added_on,
          `heart-rate`.added_on;

我如何才能返回最早的日期?我的SQL非常基础,我想更多地了解这门语言。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

如果您想要最早的日期,则可以使用least表示每行的最早日期 总的来说,您可以按least订购。

SELECT least(gps.time,
       cadence.added_on,
       `heart-rate`.added_on)
FROM   gps
       JOIN cadence
         ON cadence.rider_id = gps.rider_id
       JOIN `heart-rate`
         ON `heart-rate`.rider_id = gps.rider_id
ORDER  BY least(gps.time,
          cadence.added_on,
          `heart-rate`.added_on)
LIMIT 1

答案 1 :(得分:0)

另一种变体是使用子查询:

SELECT least(
    (SELECT min(time) FROM gps),
    (SELECT min(added_on) FROM cadence),
    (SELECT min(added_on) FROM `heart-rate`)
) AS oldest;

或者获取最新条目而不是最早的条目:

SELECT greatest(
    (SELECT max(time) FROM gps),
    (SELECT max(added_on) FROM cadence),
    (SELECT max(added_on) FROM `heart-rate`)
) AS newest;