Jump to content

[SOLVED] Counting references in a one to many relationship


GeoffreyB

Recommended Posts

Hi,

I am trying to display a list of records with one of the columns in the list being a count of records in a child table.

This is what I have tried to no effect:

SELECT a.*, b.(SELECT COUNT(id) FROM training_topics WHERE subjectid=a.id AND published) FROM training_subjects as a

I get this error

Error Code : 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT COUNT(id) FROM jos_training_topics WHERE subjectid=a.id AND published) F' at line 1

I guess you can't have a subquery before the from.

I am not sure have to do this with joins?

I would greatly appreciate suggestions.

Thanks

 

Link to comment
Share on other sites

What I need is a result set that has all training subjects and each row has a column which is a count of published topics with a relationship to that subject.

Training Subject Structure

id int - autoincrement

name - varchar

published - tinyint (boolean either 0 or 1)

Training Topic Structure

id - int autoincrement

subjectid - int (reference to Training Subject table

title - varchar

topic - text

published - tinyint (boolean either 0 or 1

I hope this makes it clearer.

Thanks for answering

Link to comment
Share on other sites

Ah, well to correct your query:

SELECT ts.*, COUNT(tt.id)
FROM training_subjects ts, training_topics tt
WHERE tt.subjectid=ts.id
AND ts.published=1
GROUP BY ts.name

changed the alias a and b to reflect the names better; ts and tt

COUNT requires a GROUP BY clause, and we're grouping by the subject name

we're only showing topics that are published

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.