简体   繁体   中英

MySQL Query Speed Joins

Are there any ways that the following query could be optimised for speed? It takes about 6 seconds to execute. Each table only contains around 1000 records so it's not huge.

SELECT c. * , q.qualification_name, CONCAT( u.firstname, ' ', u.lastname ) AS name, v.venue_name, v.address_town
FROM p_courses c
LEFT JOIN p_qualifications q ON c.qualification_name = q.ref
LEFT JOIN p_users u ON c.instructor_number = u.instructor_number
LEFT JOIN p_venues v ON c.venue_token = v.token
WHERE (
c.status = 'completed'
OR c.status = 'confirmed'
)

The above query works and retrieves all data as requested, it just takes a long time as soon as I add more than one LEFT JOIN.

Thanks.

EDITED.

Adding EXPLAIN in front of the query returns this...

id  select_type table   type    possible_keys   key   key_len   ref     rows    Extra
1   SIMPLE      c       ALL     NULL            NULL  NULL      NULL    1288    Using where
1   SIMPLE      q       ALL     NULL            NULL  NULL      NULL    21   
1   SIMPLE      u       ALL     NULL            NULL  NULL      NULL    518  
1   SIMPLE      v       ALL     NULL            NULL  NULL      NULL    669

Sorry but I'm not quite sure how to interpret that.

  1. check what's wrong by putting EXPLAIN in front of your query.
  2. set your indeces so your joins and your where can use them.
  3. check you EXPLAIN again
  4. lather, rinse, repeat.

hints: you probably want an index on:

c.qualification_name 
q.ref
c.instructor_number 
u.instructor_number
c.venue_token 
v.token
c.status

From the Explain you posted it doesn't look like the query is using indexes. Ensure that q.ref, u.instructor_number and v.token are indexed

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