2016-12-29 48 views
0

我下面的表格有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 

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

+3

可能的复制[ROW \ _NUMBER()in MySQL](http://stackoverflow.com/questions/1895110/row-number-in-mysql) –

+2

[Get top n re每组分组结果](http://stackoverflow.com/questions/12113699/get-top-n-records-for-each-group-of-grouped-results) – shmosel

+0

只读通过推荐的答案,我不要解开它们 –

回答

2

为了得到独一无二的纪录ITEM_ID,你应该子句中使用组。 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 
+0

group by不提供我期望的结果 –

+0

你想要的结果与你在上面的表格中提到的一样,并且表格的记录将被修复? –

+0

'ASC'是可选 – denny

0

试试这个...不需要聚合函数...

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

支票sqlfiddle: - http://sqlfiddle.com/#!9/218a1/1

+0

感谢denny你的答案工作很好的小提琴,但我不明白为什么它不能在我的服务器上工作,我注意到的唯一不同的事情是mysql版本小提琴= 5.6我的服务器= 5.7。有任何想法吗? –

+0

@ALDI我也尝试过5.7.successfully execute.there没有任何问题。这里检查http://rextester.com/SVGEOV26849 – denny

+0

@ALDI只有日期不同的两个结果因为你忽略end_date这是过去,今天是30dec。 – denny

相关问题