优化mysql子查询语句

时间:2017-05-23 12:34:11

标签: mysql sql database

我正在制作社区分享'令人毛骨悚然的面食'。 我的查询现在需要133毫秒,但我想更快地进行查询。 只推荐一个关键字就足够了。

这是我的桌子。

  

列描述:

     

'cp_id'表示creepypasta的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

1 个答案:

答案 0 :(得分:1)

对于您的查询,您可以在#legacySQL SELECT * FROM FLATTEN(( SELECT SPLIT(Titles) AS Title FROM (SELECT 'xy,zx' AS Titles) ), Title) AS A LEFT JOIN ( SELECT Name, Title FROM table.name ) AS Names ON A.Title=Names.Title 上添加索引:

creepy_points(cp_id, creepy)