递归SQL查询。选择最后一个条目分组

时间:2013-08-19 12:02:32

标签: mysql

我有一个费率表,其中包含此价格的目的地,价格和有效日期。

我想获得一个包含最后价格的目的地列表。

示例表:

Destination  | Code | Effective_date | Price
Spain        | 34   | 2013-04-05     | 0.02
Spain        | 34   | 2013-07-01     | 0.01
Spain Mobile | 346  | 2013-04-05     | 0.07
Spain Mobile | 346  | 2013-07-01     | 0.08

例如,如果我搜索代码34,我想获得西班牙2013-07-01和西班牙移动2013-07-01 我试试

SELECT * 
FROM carrier_fares AS cf1               
WHERE NOT EXISTS (
    SELECT * FROM carrier_fares AS cf2
    WHERE code LIKE ?
    AND cf1.effective_date < cf2.effective_date
    )

该表有超过50,000个条目。

2 个答案:

答案 0 :(得分:2)

   SELECT x.*
     FROM carrier_fares x
     JOIN  
        ( SELECT destination
               , MAX(effective_date) max_date 
            FROM carrier_fares 
           GROUP 
              BY destination
        ) y
       ON y.destination = x.destination 
      AND y.max_date = x.effective_date

-- [WHERE code LIKE '34%']
;

答案 1 :(得分:-1)

SELECT * FROM (
   SELECT * FROM carriers_fares ORDER BY effective_date DESC
) as t1 GROUP by effective_date, code