add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.

CREATE TABLE post
(`id` int, `title` varchar(6))
;
INSERT INTO post
(`id`, `title`)
VALUES
(0, 'titleA'),
(1, 'titleB'),
(2, 'titleC')
;


CREATE TABLE comment
(`id` int, `id_post` int, `text` varchar(40))
;
INSERT INTO comment
(`id`, `id_post`, `text`)
VALUES
(1, 0, 'blaa'),
(2, 0, 'blbb'),
(3, 1, 'aaaa'),
(4, 1, 'bbbb')
;



CREATE TABLE comment_likes
(`id` int auto_increment primary key, `id_comment` int, `vote` int)
;
INSERT INTO comment_likes
(`id_comment`, `vote`)
VALUES
SELECT * FROM post;
SELECT * FROM comment;
SELECT * FROM comment_likes
id title
0 titleA
1 titleB
2 titleC
id id_post text
1 0 blaa
2 0 blbb
3 1 aaaa
4 1 bbbb
id id_comment vote
1 1 1
2 1 1
3 1 1
4 1 1
5 1 1
6 1 -1
7 1 1
8 2 7
9 3 5
10 3 5
11 4 1
12 4 1
13 4 1
-- SET @@sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
SELECT p.id AS post_id
, ( SELECT c.id AS comment_id
FROM comment c INNER JOIN comment_likes l ON l.id_comment = c.id
WHERE c.id_post = p.id
GROUP BY c.id
ORDER BY SUM(vote) DESC
LIMIT 1
) AS comment_id
, ( SELECT SUM(l.vote)
FROM comment c INNER JOIN comment_likes l ON l.id_comment = c.id
WHERE p.id = c.id_post
GROUP BY c.id
ORDER BY SUM(l.vote) DESC
LIMIT 1
) AS total_like_votes
FROM post p
HAVING total_like_votes IS NOT NULL
post_id comment_id total_like_votes
0 2 7
1 3 10