0

I have this MySQL query that is very slow, I presume because of all the JOINs (it seems complicated, but it's a matter of lot of tables):

SELECT DISTINCT doctors.doc_id, 
    doctors.doc_user, 
    doctors.doc_first, 
    doctors.doc_last, 
    doctors.doc_email, 
    doctors.doc_notes, 
    titles.tit_name, 
    specializations.spe_name, 
    activities.act_name, 
    users.use_first, 
    users.use_last,
    (SELECT COUNT(*) FROM locations WHERE locations.loc_doctor = doctors.doc_id) AS loc_count,
    (SELECT COUNT(*) FROM reception WHERE reception.rec_doctor = doctors.doc_id) AS rec_count,
    (SELECT COUNT(*) FROM visits INNER JOIN reports ON visits.vis_report = reports.rep_id  WHERE visits.vis_doctor = doctors.doc_id AND reports.rep_user LIKE '%s') AS vis_count
FROM
    doctors
INNER JOIN titles ON titles.tit_id = doctors.doc_title
INNER JOIN specializations ON specializations.spe_id = doctors.doc_specialization
INNER JOIN activities ON activities.act_id = doctors.doc_activity
LEFT JOIN locations ON locations.loc_doctor = doctors.doc_id
INNER JOIN users ON doctors.doc_user = users.use_id
WHERE
    ((doctors.doc_last LIKE %s) OR (doctors.doc_first LIKE %s) OR (doctors.doc_email LIKE %s)) 
    AND doctors.doc_user LIKE %s 
    AND locations.loc_province LIKE %s 
    AND doctors.doc_specialization LIKE %s 
    AND doctors.doc_activity LIKE %s 
ORDER BY %s

All the %s are parameters in a sprintf() PHP function
The most important thing to notice is... that I have NO indexes on MySQL! I presume that I can speed up the process adding some indexes... but what and where? There are so many joins and search parameters that I am in confusion about what would be efficient :-)

Please can you help? Thanks in advance!

Ivan
  • 2,463
  • 6
  • 39
  • 51

2 Answers2

0

You can start with adding indexes on those columns you are using in the where condition.

Further, you should index those fields which are used in join, i.e. primary keys and foreign keys column.

I would suggest that gradually experimenting with these indexes would yield a real performance boost.

Further, I have observed that you are fetching too much of data in a single query. If it is really not required, break it up in different reports and pages (If possible) as even if you do proper indexing, the solution will not be quite scalable and may not handle large amount of data.

Note: You might have to create full text index on fields which you query by '%' qualifier.(i.e. use LIKE operator)

Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34
0

Like operators are pretty slow. Here is a discussion of applying indexes and FULL TEXT

mysql like performance boost

Community
  • 1
  • 1
Matt Evans
  • 7,113
  • 7
  • 32
  • 64