mysql - GROUP BY 也选择非常量列

标签 mysql sql select group-by greatest-n-per-group

我的数据库中有 2 个表:

log_visitors:
--------------------
id | host_id


log_access:
--------------------
visitor | document | timestamp

log_access.visitor 链接到 log_visitors.id

目前,我正在使用这个查询:

SELECT
    log_visitors.host_id
    , MIM(log_access.timestamp) AS min_timestamp
FROM
    log_access
    INNER JOIN log_visitors
        ON (log_access.visitor = log_visitors.id)
GROUP BY log_visitors.host_id;

为数据库中的每个 host_id 获取 MIN(timestamp)

这是我的问题:

我还需要获取具有该时间戳的访问权限的document...我不能简单地将log_access.document 添加到SELECT 列表中,因为它不是常量并且我不是按文档分组... 有什么想法吗?

最佳答案

您没有指定您的 DBMS,但这是 ANSI SQL(适用于大多数现代 DBMS)

select *
from (
  SELECT log_visitors.host_id,
         log_visitors.document,
         log_access.timestamp
         min(log_access.timestamp) OVER (partition by log_visitors.host_id) AS min_timestamp
  FROM log_access
    JOIN log_visitors ON (log_access.visitor = log_visitors.id)
) t
where t.timestamp = t.min_timestamp
ORDER BY host_id

关于mysql - GROUP BY 也选择非常量列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13199601/

相关文章:

php - MySQL:选择一个获胜者,返回他们的排名

MySQL:将时间和日期转换为unix时间戳

php - 防止访问者每天发布超过 2 个帖子的方法(PHP MySQL)

sql - 选择数据库范式

javascript - 从两个单独的 JSON 对象 JQuery 使用 OptGroup 填充选择

mysql - 如何从另一个表中的字段获取计数 - MySQL

PHP数据库连接失败

javascript - 在 php 中上传图像时显示错误

mysql - 对 INT 字段执行 LIKE 比较

mysql - 用自连接替换嵌套选择查询