-1
I am having a problem with this sql query. Its return time is on average 10 seconds and ta using 100% cpu. Probably because it uses many subquery. However I’m not able to optimize it. Does anyone have any idea which way I can go ?
SELECT id_post, midia, texto, tb_usuario.id, tb_usuario.nome, user, avatar, tipo, tb_comm_post.id_categoria, tb_comm_post.data_criacao, tb_comm_categorias.nome, cor1, cor2,
(SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = 1) as n_like,
(SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = -1) as n_dislike,
(SELECT flag FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_usuario = ? AND tb_liked_comunidade.id_post = tb_comm_post.id_post) as flag,
(SELECT COUNT(*) FROM tb_comentario_comunidade WHERE tb_comentario_comunidade.id_post = tb_comm_post.id_post) as n_comentarios
FROM tb_comm_post
JOIN tb_usuario ON tb_usuario.id = tb_comm_post.id_autor
JOIN tb_comm_categorias ON tb_comm_post.id_categoria = tb_comm_categorias.id_categoria
WHERE tb_comm_post.exibir = 1
ORDER BY tb_comm_post.data_criacao DESC
LIMIT 5 OFFSET ?
Where ta the question mark "?" is that the data comes when executing the query
Try to put the data in a temporary table, right after you apply the sub-consultations.
– Marconi
Makes Join with tb_liked_community in place of subselect and deals with iif or case (pivot) , Join with tb_comment community as well.
– Motta
Run a EXPLAIN and analyze the execution plan by identifying the bottlenecks.
– anonimo
Try to do it without the Ubqueries and go back and forth one by one to see which one is picking up. Remembering that optimization of SQL query is an NP-complete problem, so every SQL server ends up "choking" with some queries, even if the optimization is obvious to a human, and ends up having to do the sub-consultations as other queries in client-side code.
– epx
The answers even give ideas of how to improve, but other problems of slowness can be caused by poorly planned modeling, doing anyway many things can fail, in this appear accusations (not that I am praising) mysql is slower q other banks, when in fact many problems are from a bad planning of the structure. I’m only commenting to complement, because you may even have obtained a "solution" in the answers, but there are things that are not enough a select "efficient"
– Guilherme Nascimento