SQL:如何每天选择一条记录,假设每天包含多于1个值的MySQL

时间:2013-05-10 10:28:55

标签: php mysql sql query-optimization sql-optimization

我想从'2013-04-01 00:00:00''today'选择记录但是,每天都有很多价值,因为他们每15分钟保存一个值,所以我只想要每个值的第一个或最后一个值一天。

表架构:

CREATE TABLE IF NOT EXISTS `value_magnitudes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value` float DEFAULT NULL,
  `magnitude_id` int(11) DEFAULT NULL,
  `sdi_belongs_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `reading_date` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1118402 ;

错误的SQL:

SELECT value FROM `value_magnitudes` WHERE `value_magnitudes`.`reading_date` BETWEEN '2013-04-01 00:00:00' AND '2013-04-02 00:00:00' AND (`value_magnitudes`.magnitude_id = 234) LIMIT 1
SELECT value FROM `value_magnitudes` WHERE `value_magnitudes`.`reading_date` BETWEEN '2013-04-02 00:00:00' AND '2013-04-03 00:00:00' AND (`value_magnitudes`.magnitude_id = 234) LIMIT 1
SELECT value FROM `value_magnitudes` WHERE `value_magnitudes`.`reading_date` BETWEEN '2013-04-03 00:00:00' AND '2013-04-04 00:00:00' AND (`value_magnitudes`.magnitude_id = 234) LIMIT 1
SELECT value FROM `value_magnitudes` WHERE `value_magnitudes`.`reading_date` BETWEEN '2013-04-04 00:00:00' AND '2013-04-05 00:00:00' AND (`value_magnitudes`.magnitude_id = 234) LIMIT 1
SELECT value FROM `value_magnitudes` WHERE `value_magnitudes`.`reading_date` BETWEEN '2013-04-05 00:00:00' AND '2013-04-06 00:00:00' AND (`value_magnitudes`.magnitude_id = 234) LIMIT 1
etc ...

如果可能的话,我想要一个人......

非常感谢你。

修改 我的意思是,我每天都有一个查询,但我只是想从reading_date >= '2013-04-01 00:00:00' c进行一次查询

EDIT2: 我在那个table.value_magnitudes中有 64,260 个记录,并且需要太长时间才能执行和响应该查询,有时还需要超时连接。

2 个答案:

答案 0 :(得分:5)

获取您可以执行的每个日期的第一个条目

select * from value_magnitudes
where id in 
(
    SELECT min(id)
    FROM value_magnitudes
    WHERE magnitude_id = 234
    and date(reading_date) >= '2013-04-01'
    group by date(reading_date)
)

答案 1 :(得分:2)

select * from value_magnitudes
where id in 
(
   SELECT min(id)
   FROM value_magnitudes
   WHERE `value_magnitudes`.`reading_date` BETWEEN '$from_selected' AND '$to_selected' and (magnitude_id = 234) group by date(reading_date)
)