I currently have a database with the following structure:
id->varchar(9)
time->datetime
val01 - val20->int(11)
val21 - val40->tinyint(1)
id and time are the primary key. also I defined an index for time.
+-----+---------------------+--------+--------+--------+...+--------+--------+--------+
| id | time | val01 | val02 | val03 |...| val38 | val39 | val40 |
+-----+---------------------+--------+--------+--------+...+--------+--------+--------+
| #01 | 2014-02-26 12:25:00 | 56 | 9 | 10 |...| 0 | 0 | 0 |
| #01 | 2014-02-26 12:26:00 | 14 | 89 58 |...| 0 | 1 | 0 |
| #01 | 2014-02-26 12:27:00 | 52 | 91 | 68 |...| 0 | 1 | 1 |
| #02 | 2014-02-26 12:28:00 | 52 | 30 | 73 |...| 0 | 1 | 1 |
....................................................................................
| #01 | 2014-02-28 16:34:00 | 32 | 82 | 86 |...| 0 | 1 | 0 |
| #01 | 2014-02-28 16:35:00 | 28 | 14 | 93 |...| 1 | 1 | 1 |
| #02 | 2014-02-28 16:35:00 | 94 | 95 | 49 |...| 0 | 0 | 0 |
| #02 | 2014-02-28 16:36:00 | 76 | 64 | 30 |...| 1 | 0 | 1 |
+-----+---------------------+--------+--------+--------+...+--------+--------+--------+
The problem is, that I will get millions of new rows everyday. The table will have about 1,8 billion rows when the service is running for a few months and I would like to prevent it from getting even larger.
Therefore I would like to delete some of the old rows, because there is no need for them anymore.
E.g: I would only keep every 5th record, that is older than 6 months. That would be about 10 000 000 rows that I could delete a day.
I tried to achieve this with this query:
SET @x := 0;
DELETE FROM mytable WHERE(id,time) IN(
SELECT id, time FROM
(
SELECT id, time, (@x:=@x+1) AS x FROM mytable
WHERE time < "2013-08-08 00:00:00"
ORDER BY time
)t
WHERE x MOD 5 != 0
)
Unfortunately this query is much to slow.
How could I improve it? Or is there a different approach that is better?