如何使用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 |
+---------+---------+-----------------------+--------+------------+---------+
我很难搞清楚这一点。谢谢!
答案 0 :(得分:3)
您可以使用group by:
select NameStore, idStore, Name, idItem, max(date) date, price
from table
group by NameStore, idStore, Name, idItem, price
答案 1 :(得分:2)
在线示例查询
http://data.stackexchange.com/stackoverflow/q/118881/how-can-i-get-the-most-resent-date-using-mysql
SELECT NameStore, idStore, Name, idItem, max(date) AS date, price
FROM tablename
GROUP by NameStore, idStore, Name, idItem, price
ORDER BY date DESC, idItem ASC
答案 2 :(得分:1)
请参阅SQL Select only rows with Max Value on a Column
SELECT yt1.*
FROM yourtable yt1
LEFT OUTER JOIN yourtable yt2 ON (yt1.idItem = yt2.idItem AND yt1.date < yt2.date)
WHERE yt2.idItem IS NULL;
答案 3 :(得分:-1)
将其放在最后ORDER BY date DESC
所以看起来像这样:
SELECT * FROM `tablename` ORDER BY `date` DESC
在上面的SQL语句中使用DISTINCT(Name)
或GROUP BY Name
会使一个项目只弹出一次。
答案 4 :(得分:-1)
您必须使用GROUP BY这样的句子:
SELECT Name, idStore, Name, idItem, date, price
FROM mytable
GROUP BY idItem
ORDER BY date DESC, idItem DESC;
使用DESC或ASC更改订单方向。您可以通过阅读文档了解更多信息。