Stanislav Stankov
Stanislav Stankov

Reputation: 135

MySQL query, how to optimize it better

I have the following queries one by one executing

delete FROM secure_dl_ipmap WHERE timestamp < (NOW() - INTERVAL {$days} DAY)

SELECT null FROM secure_dl_ddown d WHERE d.id = id_file

delete FROM secure_dl_ddown WHERE id NOT IN (SELECT i.id_file FROM secure_dl_ipmap i)

secure_dl_ddown table

no indexes. id, actuallink, whoreferred is primary

about 100k rows;

secure_dl_ipmap table

no indexes. id & refer is set as Primary

about 100k rows;

Do you have any ideas how to change queries and if needed to index the tables?

Upvotes: 0

Views: 78

Answers (1)

Benvorth
Benvorth

Reputation: 7722

Add a BTREE index on secure_dl_ipmap.timestamp and a HASH index on secure_dl_ddown.id:

ALTER TABLE secure_dl_ipmap ADD INDEX idIdx USING BTREE (timestamp);
ALTER TABLE secure_dl_ddown ADD INDEX idIdx USING HASH (id);

Background is that BTREE indices are best used for range-queries (like your "lower than"). HASH indices are fast on "equal" selectors.

EDIT

To Speed up DELETE operations you may use DELETE QUICK FROM ... as stated here:

If you are going to delete many rows from a table, it might be faster 
to use DELETE QUICK followed by OPTIMIZE TABLE. 
This rebuilds the index rather than performing many index block 
merge operations. 

EDIT2

Following a hint found on the same page try this:

DELETE secure_dl_ddown 
FROM secure_dl_ddown 
LEFT JOIN secure_dl_ipmap ON secure_dl_ddown.id=secure_dl_ipmap.id_file 
WHERE secure_dl_ipmap.id_file IS NULL

(to delete rows that exist in t1 that have no match in t2, use a LEFT JOIN)

Upvotes: 3

Related Questions