mysql找到比今天更小的最新记录

taor4pac  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(241)

请帮助mysql新手:
我有两张table:

assets

asset_id |  description
------------------------
001      |  Crate of Laptops
002      |  Crate of OhBots
003      |  Crate of Spheros

bookings

id       | asset_id   |  start_date     |     end_date   |   location
----------------------------------------------------------------------
1        | 001        |    2018/10/01   |   2018/10/10   |   Barnet
2        | 001        |    2018/10/12   |   2018/10/15   |   Hendon
3        | 002        |    2018/10/01   |   2018/10/10   |   Finchley
4        | 001        |    2018/12/01   |   2018/12/04   |   Brent

我需要显示每个资产的所有最新预订,开始日期小于今天-因此,如果今天的日期是2018/10/19,它应该为我提供预订ID的详细信息:

asset_id     |       location
------------------------------
001          |       Hendon
002          |       Finchley

到目前为止,我有这个,但它没有显示最新的预订-它显示了所有的。我想我需要一个使用max()的子查询,但无法让它工作。有许多关于如何从表中获取最新值的帖子,但我还需要将起始日期设置为过去。

SELECT asset.asset_id, asset.description, booking.location, booking.start_date
FROM  assets AS asset
INNER JOIN bookings AS booking 
ON asset.asset_id=booking.asset_id
WHERE booking.start_date <= NOW()
ORDER BY asset.asset_id DESC;
0g0grzrc

0g0grzrc1#

您可以从开始日期开始订购。试试这个,

SELECT asset.asset_id, asset.description, booking.location, booking.start_date
FROM  assets AS asset
INNER JOIN bookings AS booking 
ON asset.asset_id=booking.asset_id
WHERE booking.start_date <= NOW()
ORDER BY asset.asset_id,booking.start_date DESC;
8tntrjer

8tntrjer2#

你是正确的,你需要使用 MAX() 要在子查询中查找每个资产的最长开始日期,然后需要将其连接回 booking 表中找到其他相应的信息。

SELECT a.id, a.description, b.start_date, b.location
FROM assets a
INNER JOIN bookings b ON (a.id = b.asset_id)
INNER JOIN (
    SELECT b.asset_id, MAX(b.start_date) AS start_date
    FROM bookings b
    WHERE b.start_date < CURDATE()
    GROUP BY b.asset_id
) c ON (b.asset_id = c.asset_id AND b.start_date = c.start_date)

这是一个正在运行的数据库小提琴:https://www.db-fiddle.com/f/mci3tkzpzxkcjckwnvhrbk/0

相关问题