Given is mySQL table named "user_posts" with the following relevant fields:
indexed in all three fields
My running slow query is here and also i have created an dbFiddle . Output of Explain is in the dbfiddle:
SELECT
P.user_post_id,
P.user_id_fk,P.post_type,
P.who_can_see_post,
P.post_image_id,P.post_video_id,
U.user_name, U.user_fullname,U.influencer_status
FROM user_posts P FORCE INDEX (ix_user_posts_post_id_post_type)
INNER JOIN users U FORCE INDEX (ix_status_istatus)
ON P.user_id_fk = U.user_id
WHERE
U.user_status='1' AND
U.influencer_status = '1' AND
(P.who_can_see_post IN('everyone','influencer','friends')) AND
(P.post_type IN('image','video'))
AND p.user_post_id > 30
ORDER BY
P.user_post_id
DESC LIMIT 30
Run Code Online (Sandbox Code Playgroud)
The query takes extremely long, around 6-15 seconds. The database is not very busy otherwise and performs well on other queries.
I am obviously wondering why the query is so slow.
Is there a way to tell exactly what is taking mySQL so long? Or is there any change I need to make to make the query run faster?
ix_status_istatus密钥的定义阻止了它用于优化WHERE子句,因为它包括了user_id未在WHERE子句中使用的密钥。将索引重新定义为
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD KEY ix_status_istatus (user_status, influencer_status);
Run Code Online (Sandbox Code Playgroud)
允许其使用,并应加快您的查询,改变对搜索users使用index代替temporary and filesort。
更新资料
对dbfiddle的进一步分析表明,最好将它FORCE INDEX从P表中删除,因为它是不必要的(仅PRIMARY需要键),并将其更改JOIN为a,STRAIGHT_JOIN即写为JOINas:
FROM user_posts P
STRAIGHT_JOIN users U FORCE INDEX (ix_status_istatus)
ON P.user_id_fk = U.user_id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |