【问题标题】:mySQL - Get min, max and a property of row containing maxmySQL - 获取最小值、最大值和包含最大值的行的属性
【发布时间】:2011-11-10 04:35:32
【问题描述】:

我需要从一个表中获取三个字段。该表具有字段 - id、timestamp、viewTime。我需要用 max(timestamp) 获取记录的 min(timestamp)、max(timestamp)、viewTime。我宁愿只有一个查询。

SELECT MAX(timestamp), 
       MIN(timestamp), 
       viewTime 
  FROM session_progress 
 WHERE session_id = 2374;

此查询正确返回最小值、最大值,但返回最小查看时间。我真正想要的是具有最大时间戳的记录的视图时间。

例如:

  timestamp             viewTime 
  ----------------------------------
  2011-11-05 10:21:00          1055
  2011-11-06 15:00:00          8900
  2011-11-07 18:20:00           750
  2011-11-07 19:23:00          4200

查询返回viewTime 750,但我需要最大的viewTime,即4200。

如果答案是用grails写的,那就更好了(这与上面的SQL查询相同):

def sp_res = sp.get {
            projections {
                min("timestamp")
                max("timestamp")
                totalTime
            }
            and {
                eq("sessionId", unSession.id)
            }
        }

【问题讨论】:

  • 这个查询没有意义。只有懒惰的 MySQL 允许这种语法(这没有意义)。真正的数据库会抱怨(例如 SQL Server 会说:“Column 'session_progress.viewTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.”)
  • 什么意思?我应该使用 2 个查询吗?首先获取行,然后获取行字段?谢谢。

标签: mysql grails


【解决方案1】:
select b.maxT, b.minT, viewTime 
from session_progress,

(select max(timestamp) as maxT, min(timestamp) as minT
from session_progress 
where session_id=2374 ) b

where where session_id=2374 AND timestamp = b.maxT

这只是想法,不过我还没有测试过。请原谅任何错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多