繁体   English   中英

优化mysql子查询语句

[英]optimizing mysql sub-query statement

我正在社区共享“令人毛骨悚然的面食”。 我的查询现在需要133毫秒,但我想使查询更快。 只要推荐一个关键字就足够了。

这是我的桌子。

栏说明:

“ cp_id”表示“ creeplypasta”的ID。

“ session_id”类似于作家。

“令人毛骨悚然”是指令人毛骨悚然的面食。 当“令人毛骨悚然”为0时,这不是令人毛骨悚然的故事。 但是当它是1时,那是令人毛骨悚然的。

 - creepypastas: id, alias, created_at, modified_at, title, content, session_id
 - creepypasta_comments: id, cp_id, created_at, content, session_id
 - creepy_points: id, cp_id, creepy, session_id

这是我的SQL查询。

SELECT id, alias, created_at, modified_at, title, content, session_id, 
(SELECT COALESCE(SUM(case creepy when 1 then 1 else 0 end), 0) FROM 
creepy_points c WHERE creepypastas.id = c.cp_id) AS creepy_count, 
(SELECT COALESCE(SUM(case creepy when 0 then 1 else 0 end), 0) FROM 
creepy_points c WHERE creepypastas.id = c.cp_id) AS not_creepy_count, 
(SELECT COUNT(c.id) FROM creepypasta_comments c WHERE creepypastas.id = 
c.cp_id) AS comment_count 
FROM creepypastas ORDER BY created_at DESC

对于您的查询,您可以在creepy_points(cp_id, creepy)上添加索引:

create index idx_creepypoints_cpid_creepy on creepy_points(cpid, creepy);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM