如何按MAX(日期)选择?

poe*_*747 24 mysql sql select max

这是表结构

CREATE TABLE `reports` (
  `report_id` int(11) NOT NULL auto_increment,
  `computer_id` int(11) NOT NULL default '0',
  `date_entered` datetime NOT NULL default '1970-01-01 00:00:00',
  `total_seconds` int(11) NOT NULL default '0',
  `iphone_id` int(11) default '0',
  PRIMARY KEY  (`report_id`),
  KEY `computer_id` (`computer_id`),
  KEY `iphone_id` (`iphone_id`)
) ENGINE=MyISAM AUTO_INCREMENT=120990 DEFAULT CHARSET=latin1
Run Code Online (Sandbox Code Playgroud)

我需要一个SELECT声明,列出最新输入的report_id每个,我不知道如何做到这一点.有人能指出我正确的方向吗?Thx提前.computer_iddate_entered

bha*_*mby 46

这应该这样做:

SELECT report_id, computer_id, date_entered
FROM reports AS a
WHERE date_entered = (
    SELECT MAX(date_entered)
    FROM reports AS b
    WHERE a.report_id = b.report_id
      AND a.computer_id = b.computer_id
)
Run Code Online (Sandbox Code Playgroud)

  • 这有点低效,因为您生成了太多子查询.相反,尝试使用不相关的子查询.https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html (9认同)
  • 几乎.我遗漏了"a.report_id = b.report_id",这就是诀窍.谢谢 (2认同)
  • 巴勃罗是正确的。可以通过加入子查询来更早地进行过滤,从而节省了性能。 (2认同)

Gen*_*ume 14

您是否只希望它显示最后一个date_entered,或者从输入的last_date开始订购?

SELECT report_id, computer_id, date_entered
FROM reports
GROUP BY computer_id
ORDER BY date_entered DESC
-- LIMIT 1 -- uncomment to only show the last date.
Run Code Online (Sandbox Code Playgroud)

  • 当id执行此操作时,我得到错误的report_id.我使用WHERE computer_id = 30检查了语句.结果是所有找到的report_id的第一个report_id与最新的date_entered结合使用 (3认同)

Fra*_*jak 5

根据此: https: //bugs.mysql.com/bug.php? id=54784 转换为 char 应该可以解决问题:

SELECT report_id, computer_id, MAX(CAST(date_entered AS CHAR))
FROM reports
GROUP BY report_id, computer_id
Run Code Online (Sandbox Code Playgroud)

  • 这将为您提供最大日期,但不一定是同一行中的其他值。 (6认同)

Jer*_*emy 5

这是一个非常古老的问题,但我由于同样的问题来到这里,所以我将其留在这里以帮助其他人。

我试图优化查询,因为由于数据量太大,查询数据库花费了 5 分钟以上的时间。我的查询与已接受答案的查询类似。Pablo 的评论将我推向了正确的方向,我的 5 分钟查询变成了 0.016 秒。因此,为了帮助其他查询时间很长的人,请尝试使用不相关的子查询

OP 的示例是:

SELECT 
    a.report_id, 
    a.computer_id, 
    a.date_entered
FROM reports AS a
    JOIN (
        SELECT report_id, computer_id, MAX(date_entered) as max_date_entered
        FROM reports
        GROUP BY report_id, computer_id
    ) as b
WHERE a.report_id = b.report_id
    AND a.computer_id = b.computer_id
    AND a.date_entered = b.max_date_entered
Run Code Online (Sandbox Code Playgroud)

谢谢巴勃罗 评论。你救了我很多时间!