简体   繁体   English

Spring 引导应用程序中的聚合 SQL 函数的问题

[英]Problems with aggregate SQL functions in Spring Boot application

I'm working on a website in a Spring Bootwhich is connected to a MySQL db.我在 Spring Boot 中的网站上工作,该引导连接到 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.在数据库中,我有两个表: PlayerMatch ,我创建了一个查询,该查询应该返回一个包含他们已经玩过的比赛计数的球员列表。 The problem is that typed aggregate function count(M) doesn't and I don't know that I'm doing wrong.问题是键入的聚合 function count(M)没有,我不知道我做错了。 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.在 db 中,我有例如id = 1 的Player和两个玩Match es,另一个有一个Match ,另一个有 0 。结果我得到的是一个Player有 3 个玩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.如果我输入 M.id 而不是 count(M),我会为Player 1 获得两行(一个用于Match id),第二行是 onw 行。 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:当您在连接表上count()时,您必须使用group by语句:

@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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM