您好,我有800万行数据,需要优化Mysql查询以从该数据中获取一行。我正在使用以下查询,但是其服务器响应时间过长,导致页面加载速度出现问题
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
答案 0 :(得分:0)
这些索引可能有帮助。 (我假设id
是每个表的PRIMARY KEY
。)
ur: (deleted, userid, rating)
a: (deleted, statusid, userid)
a: (deleted, statusid, questionid)
请提供EXPLAIN SELECT ...
。
除非您需要检查COUNT(id)
是否不是id
,否则不要使用NULL
。编写它的通常方法是COUNT(*)
。
在一个地方,您正在检查deleted
的提供值。在另一种方法中,您需要对其进行硬编码。也许错了?
AND ur.deleted = 'N'
如果PRIMARY KEY
的{{1}}为q
,则将导致1行或无行。我想念什么?
id
(可能会有更多提示。请更改我建议的内容并遵循其他人的建议。然后让我们再看一遍。)