15

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
Taryn
  • 242,637
  • 56
  • 362
  • 405
Stumbler
  • 2,056
  • 7
  • 35
  • 61
  • 1
    Please specify the RDBMS that you are targeting by adding the appropriate tag (Oracle, SQL Server, MySQL, etc.). There may be answers that take advantage of language or product features that are not universally supported. Also, by tagging it with a specific RDBMS, your question may receive attention from people better suited to answer it – Taryn Mar 19 '13 at 17:34
  • Oh sure. Its MySQL: assumed the SQL was so generic in this case that it wouldn't make a difference – Stumbler Mar 19 '13 at 17:45
  • 1
    It might be straightforward sql, but you should always specify the rdbms you are using. :) – Taryn Mar 19 '13 at 17:48

2 Answers2

29

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).

peterm
  • 91,357
  • 15
  • 148
  • 157
3

It works for me

SELECT *, (select count(*) from receipt_note_stock b where 
b.receipt_note_id = a.id) from receipt_notes a
SaliproPham
  • 163
  • 2
  • 10