在一对多关系中选择COUNT

时间:2013-03-19 17:32:32

标签: mysql sql select count relational-database

两张桌子

播放器

1-∞关系(球员与球队):你如何计算每支球队有多少球员?

尝试失败:

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

2 个答案:

答案 0 :(得分:18)

尝试

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

如果某些球队没有分配球员,它将给出正确的结果事件。请参阅sqlfiddle(团队3没有玩家)。

答案 1 :(得分:1)

它对我有用

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