在INNER JOIN之后从多个表中获取最大日期

时间:2013-04-18 11:54:34

标签: mysql sql greatest-n-per-group

我有两张桌子

table 1)
ID |  HOTEL ID | NAME 
1       100      xyz 
2       101      pqr
3       102      abc


table 2)
ID | BOOKING ID | DEPARTURE DATE | AMOUNT
1         1       2013-04-12        100
2         1       2013-04-14        120
3         1       2013-04-9          90
4         2       2013-04-14        100
5         2       2013-04-18        150
6         3       2013-04-12        100

我想在mysql中获得结果,以便从MAX DEPARTURE DATE获取表2中的行。

ID | BOOKING ID | DEPARTURE DATE | AMOUNT
2         1       2013-04-14        120
5         2       2013-04-18        150
6         3       2013-04-12        100

2 个答案:

答案 0 :(得分:6)

SELECT  b.ID,
        b.BookingID,
        a.Name,
        b.departureDate,
        b.Amount
FROM    Table1 a
        INNER JOIN Table2 b
            ON a.ID = b.BookingID
        INNER JOIN
        (
            SELECT  BookingID, MAX(DepartureDate) Max_Date
            FROM    Table2
            GROUP   BY BookingID
        ) c ON  b.BookingID = c.BookingID AND
                b.DepartureDate = c.Max_date

答案 1 :(得分:-2)

好吧,

SELECT * FROM `table2` ORDER BY `DEPARTURE_DATE` DESC LIMIT 0,1

应该帮助