4

如何使用MySQL获取最近的日期?我尝试了max,但没有得到我想要的结果。我的表看起来像这样:如何使用MySQL获取最近的日期

+---------+---------+-----------------------+--------+------------+---------+ 
| Name | idStore | Name     | idItem | date  | price | 
+---------+---------+-----------------------+--------+------------+---------+ 
| walmart |  1 | Red Delicious Apples |  1 | 2011-10-22 | 0.98000 | 
| walmart |  1 | Red Delicious Apples |  1 | 2011-10-28 | 0.98000 | 
| walmart |  1 | Red Delicious Apples |  1 | 2011-10-28 | 0.98000 | 
| walmart |  1 | Red Delicious Apples |  1 | 2011-11-22 | 0.98000 | 
| walmart |  1 | Honeycrisp Apples  |  2 | 2011-10-22 | 1.98000 | 
| walmart |  1 | Sonya Apples   |  3 | 2011-10-22 | 2.88000 | 
| walmart |  1 | Gold Delicious Apples |  4 | 2011-10-22 | 0.98000 | 
| walmart |  1 | Sweet Tango Apples |  5 | 2011-10-22 | 2.48000 | 
| walmart |  1 | Granny Smith Apples |  6 | 2011-10-22 | 1.28000 | 
| walmart |  1 | Fugi Apples   |  7 | 2011-10-22 | 1.38000 | 
+---------+---------+-----------------------+--------+------------+---------+ 

我想这个表:

+---------+---------+-----------------------+--------+------------+---------+ 
| Name | idStore | Name     | idItem | date  | price | 
+---------+---------+-----------------------+--------+------------+---------+ 
| walmart |  1 | Red Delicious Apples |  1 | 2011-11-22 | 0.98000 | 
| walmart |  1 | Honeycrisp Apples  |  2 | 2011-10-22 | 1.98000 | 
| walmart |  1 | Sonya Apples   |  3 | 2011-10-22 | 2.88000 | 
| walmart |  1 | Gold Delicious Apples |  4 | 2011-10-22 | 0.98000 | 
| walmart |  1 | Sweet Tango Apples |  5 | 2011-10-22 | 2.48000 | 
| walmart |  1 | Granny Smith Apples |  6 | 2011-10-22 | 1.28000 | 
| walmart |  1 | Fugi Apples   |  7 | 2011-10-22 | 1.38000 | 
+---------+---------+-----------------------+--------+------------+---------+ 

我有很难搞清楚了这一点。谢谢!

+1

你是不是有一个很难搞清楚了这一点唯一的一个。我建议你通过给出一些你试图得到结果的代码来详细说明,所以我们可以看到它为什么不起作用。 – kasimir

回答

-1

把这个末ORDER BY date DESC

因此,使它看起来像这样:

SELECT * FROM `tablename` ORDER BY `date` DESC 

在上面的SQL语句使用DISTINCT(Name)GROUP BY Name,就会使一个项目弹出一次。

+1

但他也只想看到每个idItem一行。提示:GROUP BY? – Konerak

+0

然后看到[此链接](http://stackoverflow.com/questions/341737/mysql-changing-the-query-to-be-distinct-on-just-1-column)为不同的值 – abhinav

+0

-1 the顺序不是他所需要的;这仍然会保留重复的日期。 – Eljakim

3

您可以通过使用组:

select NameStore, idStore, Name, idItem, max(date) date, price 
from table 
group by NameStore, idStore, Name, idItem, price 
+0

谢谢你,那非常快。 – user1061392

-1

您必须使用GROUP BY条款是这样的:

SELECT Name, idStore, Name, idItem, date, price 
FROM mytable 
GROUP BY idItem 
ORDER BY date DESC, idItem DESC; 

更改使用DESC或ASC顺序方向。您可以通过阅读文档了解更多信息。

相关问题