SELECT COUNT across one-to-many relationship

霸气de小男生 提交于 2019-12-22 04:17:13

问题


For two tables

player

and

team

With a 1-∞ relationship (player to team): how would you count how many players belong to each team?

Failed attempt:

SELECT team.teamid, (SELECT COUNT(player.team) FROM player)
FROM team
LEFT JOIN player ON player.team = team.teamid

回答1:


Try

SELECT t.teamid, COUNT(p.team) player_count
FROM team t LEFT JOIN
     player p ON p.team = t.teamid
GROUP BY t.teamid

SQLFiddle

It will give correct result event if some teams don't have players assigned. See sqlfiddle for that (team 3 doesn't have players).




回答2:


It works for me

SELECT *, (select count(*) from receipt_note_stock b where 
b.receipt_note_id = a.id) from receipt_notes a


来源:https://stackoverflow.com/questions/15506512/select-count-across-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!