views:

18

answers:

2

I have a table called tblSport which contains the columns pkSportID and fldName.
I have a table called tblRespondentSport which contains the columns fkRespondentID and fkSportID.

I want to return the sport ID, the name of the sport, and the number of respondents.

Here's my query:

SELECT s.pkSportID AS id, s.fldSport AS sport, r.COUNT(*) AS count FROM tblSport AS s LEFT JOIN tblRespondentSport AS r ON s.pkSportID = r.fkSportID

I'm getting a MySQL 1064 error and it says its near the * in COUNT(). I'm new to joins so I'm sure its something trivial. Thanks in advance.

A: 

You are missing Group BY

SELECT s.pkSportID AS id, s.fldSport AS sport, COUNT(*) AS count 
FROM tblSport AS s LEFT JOIN tblRespondentSport AS r 
ON s.pkSportID = r.fkSportID
GROUP BY s.pkSportID, s.fldSport
Michael Pakhantsov
I'm getting the same error when I try that. Also, could you explain the GROUP BY?
birderic
@birderic, I corrected query. "group by" is grouped rows and calculated aggregated value.
Michael Pakhantsov
When you are doing count, you are looking to aggregate a certain field and count the number of occurences. Doing group by helps accomplish this. For example if you group by SportID, and you have two occurences of SportID number 5, it will display sportID 5 and under count, it will display two.
Mowgli
A: 

I think you need to change r.COUNT(*) to COUNT(r.*). or even just COUNT(*)

flayto