简体   繁体   English

优化mysql子查询语句

[英]optimizing mysql sub-query statement

I'm making a community shares 'creepy pasta'. 我正在社区共享“令人毛骨悚然的面食”。 My query takes 133ms now, but I wanna make the query faster. 我的查询现在需要133毫秒,但我想使查询更快。 just recommending a keyword is enough. 只要推荐一个关键字就足够了。

here are my tables. 这是我的桌子。

Column Description: 栏说明:

'cp_id' means creepypasta's id. “ cp_id”表示“ creeplypasta”的ID。

'session_id' is something like writer. “ session_id”类似于作家。

'creepy' means how creepy the creepy pasta is. “令人毛骨悚然”是指令人毛骨悚然的面食。 when 'creepy' is 0, it's not creepy story. 当“令人毛骨悚然”为0时,这不是令人毛骨悚然的故事。 but when that is 1, it's creepy. 但是当它是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

and here's my SQL query. 这是我的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