Mysql在具有特定订单的日期之间获得唯一记录

时间:2016-12-29 06:46:59

标签: php mysql

我有下表

    id | item_id | start_date |  end_date  | disc_percent
    1  |  1      | 2016-12-27 | 2016-12-31 |    50
    2  |  2      | 2016-12-27 | 2016-12-31 |    50
    3  |  3      | 2016-12-27 | 2016-12-31 |    50
    4  | 137     | 2016-12-27 | 2016-12-31 |    50
    5  | 1       | 2016-12-28 | 2016-12-29 |    10

我正在运行此查询:

SELECT * 
from onsale 
WHERE  (CURDATE() BETWEEN onsale.start_date 
                      AND onsale.end_date) 
order by onsale.start_date DESC, 
         onsale.end_date ASC

我想只得到每个item_id的第一条记录:

    id | item_id | start_date |  end_date  | disc_percent
    5  |  1      | 2016-12-28 | 2016-12-29 |    10
    2  |  2      | 2016-12-27 | 2016-12-31 |    50
    3  |  3      | 2016-12-27 | 2016-12-31 |    50
    4  | 137     | 2016-12-27 | 2016-12-31 |    50

我怎样才能得到这个结果? 谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

要获取 item_id 的唯一记录,您应该使用 group by 子句。 group by 子句返回表的唯一行。

查询将是这样的 -

SELECT * 
from onsale 
WHERE  (CURDATE() BETWEEN onsale.start_date 
                      AND onsale.end_date) group by item_id
order by onsale.start_date DESC, 
         onsale.end_date ASC

答案 1 :(得分:0)

试试这个......不需要聚合功能......

select * from (select * from onsale order by start_date desc) onsale group by item_id;

检查sqlfiddle : - http://sqlfiddle.com/#!9/218a1/1