How to get average with orderBy Desc in Laravel 5

后端 未结 3 1138
长情又很酷
长情又很酷 2021-01-20 21:07

I have 2 tables in my database.

books and ratings

in books id, name

in ratings

3条回答
  •  心在旅途
    2021-01-20 21:31

    That query would look something like this:

    SELECT book.id, AVG(ratings.rating) AS avg_rating 
    FROM ratings
    JOIN book ON book.id = ratings.book_id
    /* WHERE AVG(ratings.rating) > 4 You could say only return results where rating > 4 */
    GROUP BY book.id
    ORDER BY AVG(ratings.rating) DESC LIMIT 5;
    

    You need to join the two tables, use an aggregate function with a group by on the book. Then just sort and limit the results.

    UPDATE:

    In response to your question:

    SELECT book.id, COALESCE(AVG(ratings.rating), 0) AS avg_rating 
    FROM book
    *LEFT* JOIN ratings ON book.id = ratings.book_id    
    GROUP BY book.id
    ORDER BY AVG(ratings.rating);
    

    Use of a view might be something of a compromise between ease of the ORM and sanity in your querying.

提交回复
热议问题