I have a MySQL InnoDB table with about 1GB of records and growing.
each record in this table has, among other fields two date fields :
- AddedDateRecord – The date the record was added (datetime).
- LastUpdatedRecord – The date the record was last updated (datetime).
The problem is that if i want to find all records relevant for a single date i have to use 3 "OR" statements. assuming "date" is the date I need :
- AddedDateRecord >= date:00:00:00 AND AddedDateRecord <= date:23:59:59
OR
- LastUpdatedRecord >= date:00:00:00 AND LastUpdatedRecord <= date:23:59:59
OR
- AddedDateRecord <= date:00:00:00 AND LastUpdatedRecord >= date:00:00:00
I'm sure you can see the performance hit for using these 3 ORs in a Query on a 1GB records table;
I'm looking for a solution that does not involve moving away from MySQL.
Any help would be greatly appreciated.
Thanks
Best Answer
No
INDEX
can handle thatOR
. Nor can any combination of indexes.UNION
can help with the first 2 range tests, but it won't help with the 3rd.The 3rd range may include one-fourth of the table.
Is there any limit on the time between Adding and Updating? We might be able to use a partitioning or spatial trick with that information.
Barring that, I recommend a
UNION DISTINCT
of the 3 tests, together with these two indexes:The
UNION
is needed because MySQL is not good withORs
.The
DISTINCT
is important because you can get dups. To be faster, change toALL
and worry about the case where both columns are exactlydate:00:00:00
-- where all 3 tests succeed.Don't trust what you find for
LIMIT
, unless there is a significant pattern to the order how the rows were inserted. Also, we need to see thePRIMARY KEY
.