Groupby遗漏了记录

时间:2015-08-22 14:53:04

标签: mysql

我正在尝试在我的网站上显示目标主管,并发现我的查询存在问题。有问题的比赛有3个进球者,但有一名球员得分两次。以下查询将返回两个玩家,其中第二个玩家具有num_goals = 2

SELECT p.lastname, pg.time,  COUNT(pg.id) as num_goals,
FROM `exp_tm_player_goals` pg
JOIN exp_tm_players p ON ( p.id = pg.player )
WHERE `match` ='101565'
AND `team` ='202'
Group By p.id

以上给出了以下结果

lastname    time     numgoals   
Hunter      50       1
Lynn        75       2

再次查看后,这是预期的行为,以下内容将返回正确的数字。

SELECT p.lastname, pg.time, 
FROM `exp_tm_player_goals` pg
JOIN exp_tm_players p ON ( p.id = pg.player )
WHERE `match` ='101565'
AND `team` ='202'

结果

lastname    time   
Hunter      50      
Lynn        75       
Lynn        90    

但我希望做的是团队成员以及时间,所以有可能有名字,姓氏,时间,

lastname    time   
Hunter      50      
Lynn        75,90

1 个答案:

答案 0 :(得分:1)

你想要的是场外时间的group_concat。所以你第一次查询几乎是正确的:

SELECT p.lastname, GROUP_CONCAT(pg.time SEPARATOR ','), COUNT(pg.id) as num_goals
FROM `exp_tm_player_goals` pg
JOIN exp_tm_players p ON ( p.id = pg.player )
WHERE `match` ='101565'
AND `team` ='202'
Group By p.id

有关所有可能性,请参阅https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat