How do you go about setting an index to be used for a column comparison like WHERE col1 > col2?
col1 and col2 are of DATETIME type.
|
How do you go about setting an index to be used for a column comparison like
|
||||
|
Suppose the table's layout is as follows:
You may want to try one of two things IDEA #1 : Create a column to store difference in secondsCreate the column and populate as follows
If your table does not have foreign keys or constraints, do this instead:
Once done, your query would essentially
IDEA #2 : Create a separate table to store difference in seconds
Once done, your query would essentially
for
for Give it a Try !!! |
|||
|
|
|
There's no straight-forward way of doing it in MySQL. One workaround would be to store the value of comparison in another column, let's say cmp, put an index on it and use it instead of WHERE col1 > col2. You might store -1 if col1 < col2, 0 if col1 = col2, or 1 if col1 > col2. This way you could easily get results for <, <=, =, >=, > and <> comparisons. The easiest way to keep the cmp value in sync with values in col1 and col2 would be to update it in your application code whenever value of col1 or col2 is updated. If your data is updated from more than one application or you don't want to put update logic in your app, you could use an UPDATE and INSERT trigger to calculate and update the value in cmp. |
|||
|
|
col1andcol2are on the same table? – ypercube Dec 19 '12 at 12:59