简体   繁体   中英

MYSQL Query Optimization with subqueries and joins

Hi I have 8 million row data and need to optimize Mysql query to fetch a row from that data. I am using below query but its server response time is too high that creating issue in page loading speed

SELECT q.id
     , q.title
     , q.question
     , q.price
     , q.created
     , q.userid
     , q.duedate
     , q.tags
     , s.id subjectid
     , sc.id subcategoryid
     , s.title subject
     , sc.title subcategory
     , q.statusid
     , (SELECT  COUNT(id) FROM tbl_answers a WHERE a.questionid = q.id AND a.statusid = 1 AND a.deleted = 'N') q_num_answers
     , u.username
     , u.image
     , u.gender
     , (SELECT  COUNT(id) FROM tbl_answers a WHERE a.userid = q.userid AND a.statusid = 1 AND a.deleted = 'N') num_answers
     , (SELECT  COUNT(id) FROM tbl_questions WHERE userid = q.userid AND statusid = 1 AND deleted = 'N') AS num_questions
     , 0 amt_earned
     , 0 amt_spent
     , 0 num_sold
     , (SELECT  COUNT(ur.id) FROM tbl_users_ratings ur WHERE ur.userid = q.userid AND ur.deleted = 'N') u_num_ratings
     , (SELECT  COALESCE(SUM(ur.rating), 0) FROM tbl_users_ratings ur WHERE ur.userid = q.userid AND ur.deleted = 'N') u_score
  FROM tbl_questions q
  JOIN tbl_subjects s 
    ON q.subject = s.id
  JOIN tbl_subjects sc 
    ON q.subcategory = sc.id
  LEFT 
  JOIN tbl_users u 
    ON u.id = q.userid
 WHERE q.deleted = '$show_deleted' 
   AND q.id = ? 
 LIMIT 1

These indexes may help. (I am assuming that id is the PRIMARY KEY of each table.)

ur:  (deleted, userid, rating)
a:  (deleted, statusid, userid)
a:  (deleted, statusid, questionid)

Please provide EXPLAIN SELECT ... .

Don't use COUNT(id) unless you need to check for id not being NULL . The usual way to write it is COUNT(*) .

In one place you are checking for a provided values for deleted . In another, you hard code it. Perhaps wrong?

AND  ur.deleted = 'N'

If the PRIMARY KEY for q is id , then this will lead to either 1 row or no row. What am I missing?

    WHERE  q.deleted = '$show_deleted'
      AND  q.id = ?

(There may be more tips. Please change the things I suggested and follow the suggestions from others. Then let's have another look.)

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