优化后的SQL如下:

SELECT post.id,
       post.vote_id,
       post.title,
       post.user_id,
       post.user_nickname,
       post.ctime,
       post_text.content,
       post.ptime,
       post.ptime_ms,
       post.view_count,
       post.status,
       post.like_count,
       post.forward_count,
       post.comment_count,
       post.type,
       post.origin_type,
       post.origin_post_id,
       post.last_post_id,
       post.favorite_count,
       post.post_source,
       post.fund_forum_id,
       post.weight_v2
FROM `post`
JOIN post_text ON post.id = post_text.post_id
LEFT JOIN community.post_file ON post.id = post_file.post_id AND post_file.type = 1 AND post_file.status = 0
WHERE post.status = 2
  AND post.id NOT IN (4682, 2844, 2669)
  AND (post.app_module = 0 OR (post.app_module = 1 AND post.recommended = 1))
  AND post_file.post_id IS NULL
GROUP BY post.id
ORDER BY post.weight_v2 DESC, post.ptime_ms DESC, post.id DESC
LIMIT 20;
SELECT post.id,
       post.vote_id,
       post.title,
       post.user_id,
       post.user_nickname,
       post.ctime,
       post_text.content,
       post.ptime,
       post.ptime_ms,
       post.view_count,
       post.status,
       post.like_count,
       post.forward_count,
       post.comment_count,
       post.type,
       post.origin_type,
       post.origin_post_id,
       post.last_post_id,
       post.favorite_count,
       post.post_source,
       post.fund_forum_id,
       post.weight_v2
FROM `post`
JOIN post_text ON post.id = post_text.post_id
INNER JOIN community.post_file ON post.id = post_file.post_id AND post_file.type = 1 AND post_file.status = 0
WHERE post.status = 2
  AND post.id NOT IN (4682, 2844, 2669)
  AND (post.app_module = 0 OR (post.app_module = 1 AND post.recommended = 1))
GROUP BY post.id
ORDER BY post.weight_v2 DESC, post.ptime_ms DESC, post.id DESC
LIMIT 10;

优化说明:

  1. 将左连接(LEFT JOIN)改为内连接(INNER JOIN),提高查询效率。
  2. 修改表连接顺序,先连接主表post,再连接关联表post_textcommunity.post_file,可以减小连接的数据规模,提高查询效率。
  3. 将子查询中的post_file.post_id IS NULL条件移至主查询的WHERE语句中,避免使用子查询,简化SQL语句。
  4. 对JOIN和WHERE条件进行逻辑判断时,使用括号将条件分组,提高查询语句的可读性。
SQL优化:提高查询效率的技巧

原文地址: https://www.cveoy.top/t/topic/pSxu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录