I have a query that generates a list of website topics from our CMS database. In addition to what it pulls from the database, the page also shows page counts for each topic, and the counting is done in the code, not the SQL. It’s worked well for a number of years.
As time has passed, we’ve added a lot of content, so now I want to be able to sort by page count. So that means adding COUNT to the query.
The old query looked like this:
SELECT pagetopics.topic_id
, pagetopics.topic_name
, pagetopics.contact_id
, pagetopics.office
, pagetopics.publish
, pagecontacts.page_name
, pagecontacts.page_title
, pagecontacts.contact_id AS defaultcontact
, maindir.main_id
, maindir.first_name & ' ' & maindir.last_name AS fullname
FROM ( pagetopics
LEFT JOIN pagecontacts
ON pagetopics.topic_id = pagecontacts.topic_id
)
LEFT JOIN maindir
ON maindir.main_id = pagetopics.contact_id
I’ve tried to tweak it like this:
SELECT pagetopics.topic_id
, pagetopics.topic_name
, pagetopics.contact_id
, pagetopics.office
, pagetopics.publish
, pagecontacts.page_name
, pagecontacts.page_title
, pagecontacts.contact_id AS defaultcontact
, maindir.main_id
, maindir.first_name & ' ' & maindir.last_name AS fullname
, COUNT(pagecontacts.page_id) AS pages
FROM ( pagetopics
LEFT JOIN pagecontacts
ON pagetopics.topic_id = pagecontacts.topic_id
)
LEFT JOIN maindir
ON maindir.main_id = pagetopics.contact_id
GROUP BY pagetopics.topic_id
, pagetopics.topic_name
, pagetopics.contact_id
, pagetopics.office
, pagetopics.publish
, pagecontacts.page_name
, pagecontacts.page_title
, pagecontacts.contact_id
, maindir.main_id
, maindir.first_name & ' ' & maindir.last_name
And of course my count is 1 for every topic. I think I made to do a subquery, but I’m not having any epiphanies. Any advice?