繁体   English   中英

MYSQL的MAX MIN日期范围

[英]MAX MIN date ranges for MYSQL

这正在使用Joomla数据库类,但希望这是有道理的。 我需要根据某些日期范围返回最大日期和最小日期。 我遇到的问题是,对于每个日期,我还需要version_id。 我编写的查询仅返回最大日期值的版本。 我要结束的是最小日期和最小日期值的版本ID,以及最大日期和最大日期值的版本ID。 我认为这可能是工会的一个案例,但我不确定如何做到。

$query->select('a.ucm_type_id, a.ucm_item_id, a.version_id, MIN(a.save_date), MAX(a.save_date)')
    ->from($db->quoteName('#__ucm_history') . ' AS a')
    ->where('a.save_date BETWEEN ' . $db->quote($from_date) . ' AND ' . $db->quote($to_date))
    ->where('a.ucm_type_id IN (' . implode(',',$db->quote($content_type_ids)) . ')')
    ->group(array('a.ucm_type_id', 'a.ucm_item_id', ));
    // Join over the users for the checked out user.
    $query->select('b.type_title AS type')
    ->join('LEFT', '#__content_types AS b ON b.type_id=a.ucm_type_id');

    $db->setQuery($query);

仅当version_id字段在功能上依赖于ucm_type_iducm_item_id您的查询才符合sql标准。 在某些sql模式下,MySQL允许进行类似查询,因为version_id的值不确定,这可能会引起一些麻烦。 Fortunatley,在最新的mysql版本中,此模式默认为关闭。

您需要在子查询中获取日期范围内的最大日期和最小日期,并将其重新加入原始表中,以获取与这些日期关联的其他字段。

在sql中,您的查询将类似于以下内容:

select a.ucm_type_id,
       a.ucm_item_id,
       a.version_id,
       a.save_date,
       if(a.save_date=t1.min_save_date, 'min','max') as min_or_max,
       b.type_title AS type 
from `#__ucm_history` a
inner join
    (select `ucm_type_id`, `ucm_item_id`, MIN(save_date) as min_save_date, MAX(save_date) as max_save_date
     from `#__ucm_history`
     where ucm_type_id IN (...)
           and save_date BETWEEN ... and ...
     group by `ucm_type_id`, `ucm_item_id`
    ) t1 on a.ucm_type_id=t1.ucm_type_id and a.ucm_item_id=t1.ucm_item_id
left join `#__content_types` AS b ON b.type_id=a.ucm_type_id
where a.save_date=t1.min_save_date or a.save_date=t1.max_save_date

...部分替换为来自php代码的参数。

在sql环境中测试并调整查询,对查询满意后,即可使用ORM工具实施查询。 但是我的猜测是您将需要将其作为原始sql语句运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM