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)
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)
根据此: 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)
这是一个非常古老的问题,但我由于同样的问题来到这里,所以我将其留在这里以帮助其他人。
我试图优化查询,因为由于数据量太大,查询数据库花费了 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)
谢谢巴勃罗的 评论。你救了我很多时间!
| 归档时间: |
|
| 查看次数: |
185339 次 |
| 最近记录: |