views:

21

answers:

1
+1  Q: 

Optimize SQL Query

Hi, I have following query on a MySQL DB:

SELECT *  , r.id, x.real_name AS u_real_name, u.real_name AS v_real_name, y.real_name AS v_real_name2
FROM url_urlaube r
LEFT JOIN g_users u ON ( r.v_id = u.id )
LEFT JOIN g_users x ON ( r.u_id = x.id )
LEFT JOIN g_users y ON ( r.v_id2 = y.id )
WHERE (
(
FROM_UNIXTIME( 1283205600 ) >= r.from
AND FROM_UNIXTIME( 1283205600 ) <= r.to
)
OR (
FROM_UNIXTIME( 1280613600 ) >= r.from
AND FROM_UNIXTIME( 1280613600 ) <= r.to
)
OR (
FROM_UNIXTIME( 1280613600 ) < r.from
AND FROM_UNIXTIME( 1283205600 ) > r.to
)
)
ORDER BY r.from ASC

I tried to optimize this query by adding an index on (r.from, r.to) but i didn't worked.

when i let me explain this Query it says:

+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-----------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref         | rows | Extra                       |
+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-----------------------------+
|  1 | SIMPLE      | r     | ALL    | from          | NULL    | NULL    | NULL        |   42 | Using where; Using filesort |
|  1 | SIMPLE      | u     | eq_ref | PRIMARY       | PRIMARY | 4       | res.r.v_id  |    1 |                             |
|  1 | SIMPLE      | x     | eq_ref | PRIMARY       | PRIMARY | 4       | res.r.u_id  |    1 |                             |
|  1 | SIMPLE      | y     | eq_ref | PRIMARY       | PRIMARY | 4       | res.r.v_id2 |    1 |                             |
+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-----------------------------+
4 rows in set (0.00 sec)

why?

Thank you for help.

A: 

Compound index will not help you here because you have conditions with different comparing functions. Try adding separate indexes on r.from and r.to. In fact, I think one index on r.from will be enough.

FractalizeR