Answer the question
In order to leave comments, you need to log in
How to order the selection by the number of related entities?
Good afternoon!
There is a post entity post
id | body ....
and a many-to-one associated likes-dislikes entity
id | post_id | direction .....
The direction field is to store an enum with @Enumerated(EnumType.STRING), i.e. it contains two possible string values 'UP' or 'DOWN'
We need to make a selection of posts ordered by rating , which is calculated conditionally as count(UP) - count(DOWN)
That is, something like
select p, ( count(***) - count(***) ) as post_rate
from Post p join Vote v on p.id = v.post.id
group by p.id order by post_rate desc
Answer the question
In order to leave comments, you need to log in
If direct contains only 'UP' and 'DOWN', then in MySQL you can calculate the rating like this:
SUM(IF(v.direct = 'UP', 1, -1)) AS post_rate
A more universal version that works in other DBMS:
SUM(CASE WHEN v.direct = 'UP' THEN 1 ELSE -1 END) AS post_rate
If there can be more options, the expression is more cumbersome:SUM(CASE WHEN v.direct = 'UP' THEN 1 WHEN v.direct = 'DOWN' THEN -1 ELSE 0 END) AS post_rate
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question