I have two tables with one referencing the other.
CREATE TABLE blogs (
article LONGTEXT,
id VARCHAR(255) PRIMARY KEY
);
CREATE TABLE blog_eval (
blog_id VARCHAR(255) REFERENCES blogs(id) ON DELETE CASCADE,
user_id VARCHAR(255) REFERENCES users(id),
is_like BOOLEAN, --true if like / false if dislike
PRIMARY KEY (blog_id, user_id)
);
I need all blogs with two additional columns: sum of likes and sum of dislikes.
How do I combine a JOIN with the COUNT function and also distinguish between likes and dislikes?
3
Answers
One option uses conditional counts:
Since
is_like
is a boolean (an integer in essence), expressionsum(is_like)
counts the true values. Pre-aggregating in a subquery might help efficiency here.In recent MySQL versions (>= 8.0.14), we can express this with a lateral join, which might perform better:
Join the two tables, and use
SUM()
to total the likes and dislikes.Can’t you just get all the data you need from the one table?