V
V
vladflip2015-07-14 18:44:39
MySQL
vladflip, 2015-07-14 18:44:39

Complex select in mysql with 3 tables?

There are tables: (simplified)
------------------------
feedbacks
------------------- -----
id text
1 Good
2 Awful
------------------------
feedbacks_likes
-------------- ----------
feedback_id user_id
1 1
1 2
2 1
2 2
------------------------
feedbacks_dislikes
----- -------------------
feedback_id user_id
1 1
There is a user table (does not need a description) and a feedback table (feedbacks). Each review has likes and dislikes. The table of likes (feedbacks_likes) and dislikes (feedbacks_dislikes) is done in a many-to-many relationshipbetween the users table and the feedback table . The system is similar to rating videos in youtube.
Query:
Select all feedbacks and sort them by likes and dislikes.
I will be grateful for answers in the form of sql code, laravel php code or pseudocode.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2015-07-14
@vladflip

select text, (select count(*) from feedbacks_likes where feedback_id = feedbacks.id) as likes, (select count(*) from feedbacks_dislikes where feedback_id = feedbacks.id) as dislikes from feedbacks

Easy select, only the base structure is stupid.
Ideally, store the finished number of likes and dislikes so as not to count each time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question