简体   繁体   中英

Improve JOIN query speed

I have this simple join that works great but is HORRIBLY slow I think because the tech table is very large. There are many instances of uid as it tracks timestamp of the uid thus the distinct. What is the best way to speed this query up?

SELECT DISTINCT tech.uid, 
                listing.empno, 
                listing.firstname, 
                listing.lastname 
FROM   tech, 
       listing 
WHERE  tech.uid = listing.empno 
ORDER  BY listing.empno ASC 

First add an Index to tech.UID and listing.EmpNo on their respective tables. After you are sure there are indexes you can try to re-write your query like this:

SELECT DISTINCT tech.uid, listing.EmpNo, listing.FirstName, listing.LastName
FROM  listing INNER JOIN tech ON tech.uid = listing.EmpNo
ORDER BY listing.EmpNo ASC;

If it's still not fast enough, put the word EXPLAIN before the query to get some hints about the execution plan of the query.

EXPLAIN SELECT DISTINCT tech.uid, listing.EmpNo, listing.FirstName, listing.LastName
    FROM  listing INNER JOIN tech ON tech.uid = listing.EmpNo
    ORDER BY listing.EmpNo ASC;

Posts the Explain results so we can get better insight.

Hope it helps,

  1. This is very simple query. Only thing you can do in SQL - you may add indexes on fields used in JOIN/WHERE and ORDER BY clauses (tech.uid, listing.empno), if there are no indexes.

  2. If there are JOIN fields with NULL values - they may ruin your performance. You should filter them in WHERE clause ( WHERE tech.uid is not null and listing.empno not null ). If there are many rows with JOIN on NULL field - that data may produce cartesian result (not sure how is this called in english) with may contain enormous count of rows.

  3. You may change MySQL configuration. There are many options useful for performance tuning, like key_buffer_size, sort_buffer_size, tmp_table_size, max_heap_table_size, read_buffer_size etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM