Answer the question
In order to leave comments, you need to log in
How to optimize SQL Join + Expresssion?
There is a view:
create view posts_view as
select p.*,
case when pl.likes is null then 0 else pl.likes end
-
case when pdl.dislikes is null then 0 else pdl.dislikes end
as rating
from posts as p
left join (select
count(*) as likes,
post_id
from post_rate
where rate = 1
group by post_id) as pl
on p.id = pl.post_id
left join (select
count(*) as dislikes,
post_id
from post_rate
where rate = -1
group by post_id) as pdl
on p.id = pdl.post_id;
select * from posts_view order by rating limit 5;
Answer the question
In order to leave comments, you need to log in
Everything is bad:
1.
case when pl.likes is null then 0 else pl.likes end
coalesce(pl.likes)
select pr.id, sum(pr.rate) as rating
from posts as p
left join post_rate pr on pr.post_id = p.id
group by p.id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question