[英]Count rows by foreign key
I need a little help some a sql queries. 我需要一些SQL查询的帮助。 To summarise, I have 2 tables.
总结一下,我有2张桌子。
Player
(which represents a sports player) and a Goal
(which represents a goal a player scores). Player
(代表体育玩家)和Goal
(代表玩家得分的目标)。 A Player can have many Goals and linked using a foreign key on the goal table ( player_id
). 玩家可以有多个目标,并且可以使用目标表上的外键(
player_id
)进行链接。
What I want to do is get a list of "top scoring players" (top 5), but I have no idea where to start to do this using MySQL. 我想做的是获取“得分最高的玩家”列表(前5名),但是我不知道从哪里开始使用MySQL。 In PHP I'm getting all the goals, then with each goal counting how many player_id's appear and group them like that (then with the array of players and their goal count, trimming the array down to 5).
在PHP中,我得到了所有目标,然后每个目标都计数出现了多少player_id并将其分组(然后按玩家数组及其目标计数,将数组减少到5个)。 It works, but I'm almost positive I can do the counting in MySQL.
它可以工作,但是我几乎可以肯定我可以在MySQL中进行计数。
How should I approach this? 我应该如何处理?
EDIT 编辑
Tables look like 桌子看起来像
Player 播放机
ID
Name
Goal 目标
player_id
scored_against
time
SELECT COUNT(PLAYER.PLAYER_ID) as Goals,PLAYER_NAME
FROM PLAYER, GOAL
WHERE GOAL.PLAYER_ID = PLAYER.PLAYER_ID
GROUP BY GOAL.PLAYER_ID
ORDER BY Goals DESC
LIMIT 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.