SQL: How to select one record per day, assuming th

2020-06-16 18:14发布

I want to select records from '2013-04-01 00:00:00' to 'today' but, each day has lot of value, because they are saving each 15 minutes a value, so I want only the first or last value from each day.

Table schema:

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 ;

Bad 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 ...

I want all in one if possible...

Thank you a lot.

EDIT: I mean, I have a query per day, but I just want to make a single query from reading_date >= '2013-04-01 00:00:00'c

EDIT2: I have 64,260 records in that table.value_magnitudes and it takes sooooooooo long to excecute and response that query, and sometimes timeout conection.

2条回答
放荡不羁爱自由
2楼-- · 2020-06-16 18:45
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)
)
查看更多
叼着烟拽天下
3楼-- · 2020-06-16 18:52

To get the first entry for every date you can do

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)
)
查看更多
登录 后发表回答