Can I fetch the corresponding value of an aggregate from another table in a many to many database using group by in MySQL?

12 views Asked by At

So given this schema:

CREATE TABLE reviewers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL
);
 
CREATE TABLE series (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(100),
    released_year YEAR,
    genre VARCHAR(100)
);
 
CREATE TABLE reviews (
    id INT PRIMARY KEY AUTO_INCREMENT,
    rating DECIMAL(2 , 1 ),
    series_id INT,
    reviewer_id INT,
    FOREIGN KEY (series_id)
        REFERENCES series (id),
    FOREIGN KEY (reviewer_id)
        REFERENCES reviewers (id)
);

I want to find for each series, the maximum rating that each series has gotten and the name of the reviewer that has given it all in one table.

I have already tried the following, but it seems like I'm missing something:

select s.title, MAX(r.rating), CONCAT(rs.first_name, ' ',rs.last_name) as reviewer from series s 
inner join reviews r on s.id = r.series_id
inner join reviewers rs on rs.id = r.reviewer_id
group by title, reviewer
order by title;

I also tried using this as a subquery to perform another aggregate but to no avail. Is it not possible to do it this way? If not, then how? I couldn't find anything regarding this online.

0

There are 0 answers