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 eg Player
with id
= 1 and two played Match
es, another with one Match
, and another with 0. What I get as a result is one Player
with 3 played Match
es. 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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.