请帮助MySQL新手:
我有2张桌子:
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()的子查询,但无法正常工作。关于如何从表中获取最新值的文章很多,但我也需要过去的start_date。
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;
答案 0 :(得分:1)
您是正确的,您需要使用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
答案 1 :(得分:-1)
您可以在开始日期之前订购。 试试这个,
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;