MySQL - 获取最近的日期并显示表中的每一行

时间:2015-03-25 10:32:20

标签: mysql sql date join

我有2张桌子 - 设备和预订。

设备表如下所示:

ID     NAME
1      termo
2      hydro
3      force
4      hammer

预订表:

ID     EQUIPMENT_ID     START         END
1      2                25.3.2015     26.3.2015
2      2                26.3.2015     27.3.2015
3      1                28.3.2015     29.3.2015
4      3                27.3.2015     28.3.2015

我希望能够在每个设备的当前日期打印所有设备和最近的日期。

因此,当日期为(24.3.2015)时,输出看起来像这样:

NAME      START       END
termo     28.3.2015   29.3.2015
hydro     25.3.2015   26.3.2015
force     27.3.2015   28.3.2015
hammer    null        null

我尝试了一些嵌套查询,但没有运行。要查找当前日期最近的未来日期,我知道

  

SELECT start FROM reservations WHERE start> NOW()ORDER BY开始   限制1

但我不知道如何加入表格以找到每台设备的最近日期。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为相关子查询是最简单的方法。但是,您需要预订表中的三列,所以让我们获取ID并加入其余部分:

select e.*,
       (select r.id
        from reservations r
        where r.equipment_id = e.id and r.start > now()
        order by r.start asc
        limit 1
       ) as next_resid
from equipment e;

然后,连接需要一个子查询:

select e.name, r.start, r.end
from (select e.*,
             (select r.id
              from reservations r
              where r.equipment_id = e.id and r.start > now()
              order by r.start asc
              limit 1
             ) as next_resid
      from equipment e
     ) er join
     reservations r
     on er.next_resid = r.id;

请注意,end不是列的好名称。虽然它不是MySQL保留字,但它是一个SQL关键字。