php - 如何使用 MySQL 获取最新日期

标签 php mysql database relational-database greatest-n-per-group

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

+---------+---------+-----------------------+--------+------------+---------+
| 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 |
+---------+---------+-----------------------+--------+------------+---------+

我很难弄明白这一点。谢谢!

最佳答案

您可以使用分组方式:

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

关于php - 如何使用 MySQL 获取最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8238869/

相关文章:

mysql - 设置 DATE 或 DATETIME 默认值时 MySQL 出错

mysql - firebird db 如何处理用户身份验证?

Java derby 数据库服务器将不再启动

php - ERR_SSL_VERSION_OR_CIPHER_MISMATCH- 在我的网站 RiteOnPolish.com 上

php - 在生产环境中重置 Laravel 迁移

php - 如何显示页面 ID 中的行

php - 数据库中的触发器应该更改不同数据库中表中的值?

php - 使用触发器通过外键创建新值

php - Mysql通过VARCHAR字段插入订单号

database - 你如何管理数据库中的 "pick lists"