Problems with aggregate SQL functions in Spring Boot application

Tags: , ,



I’m working on a website in a Spring Bootwhich is connected to a MySQL db. In the db i have two tables: Player and Match and i created a query that should return me a list of players with count of matches they already played. The problem is that typed aggregate function count(M) doesn’t and I don’t know that I’m doing wrong. In db I have e.g. Player with id = 1 and two played Matches, another with one Match, and another with 0. What I get as a result is one Player with 3 played Matches. If i type M.id instead of count(M), I get two rows for Player 1 (one for Match id), and onw row for the second. What is wrong with my code?

@Query( "select new dto.PlayerDTO(" +
        "   P.id, " +
        "   P.nickname, " +
        "   count(M), " +
        "from " +
        "   Player P left join Match M on P = M.player " +
        "where " +
        "   P.games like %?1% ")
List<PlayerDTO> findPlayersForGame(String game);

Answer

When you count() on the joined table, you have to use group by statement:

@Query( "select new dto.PlayerDTO(" +
        "   P.id, " +
        "   P.nickname, " +
        "   count(M), " +
        "from " +
        "   Player P left join Match M on P = M.player " +
        "where " +
        "   P.games like %?1% " +
        "group by P.id ")
List<PlayerDTO> findPlayersForGame(String game);


Source: stackoverflow