【问题标题】:MySQL Min(), MAX() using the IDs from another tableMySQL Min(), MAX() 使用另一个表中的 ID
【发布时间】:2011-01-20 14:30:15
【问题描述】:

我有两个非常简单的 MySQL 表:Table1 具有唯一 item_ids 的列表,第二个 Table2 具有使用第一个表中的项目 id 的记录。 Table2 还包含记录的日期。在这里回顾一下表格的样子:

表 1 列:item_id

表 2 列:item_id、item_title、time_stamp

我需要的是一个 MySQL 查询,它会给我一个列表,其中包含为 Table2 中的每个 item_id 制作的第一条和最后一条记录的日期。 Table2 必须只在 Table1 中查找 item_id,因为 Table2 包含 Table1 中不包含的 item_id。所以换句话说,我使用 Table1 只是为了根据 item_id 进行排序。 非常感谢您的帮助。

【问题讨论】:

    标签: mysql sql aggregate-functions


    【解决方案1】:
    SELECT  t2.item_id, MIN(t2.time_stamp), MAX(t2.time_stamp)
    FROM    table2 t2
    JOIN    table1 t1
    ON      t1.item_id = t2.item_id
    GROUP BY
            t1.item_id
    ORDER BY
            t1.ordering_column
    

    MySQL 中,您可以在SELECTORDER BY 中使用未分组和未聚合的表达式。

    【讨论】:

    • 可能想要编辑组键并将其添加到选择列表中,以便为日期提供上下文
    • 不是 MAX() 和 MIN() 聚合表达式吗?
    【解决方案2】:
    select item_id, maxts.ts, mints.ts
    from (select item_id, max(time_stamp) as ts from Table2 group by item_id) maxts
    join (select item_id, min(time_stamp) from Table2 group by item_id) mints on maxts.item_id=mints.item_id
    join Table1.item_id t1 on t1.item_id=mints.item_id;
    

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2017-06-10
      • 2011-01-25
      相关资源
      最近更新 更多