Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Integrating COUNT() into a nested MySQL query

I have the following nested MYSQL query. Currently, out of the results, I go through and tally the tag appearances to identify the frequency. I’ve tried to integrate MYSQL’s COUNT() into my query but have been unable to.

Current query:

SELECT tagId 
FROM refTags 
WHERE postId IN (SELECT postId FROM refTags WHERE tagId = 1) 
AND tagId <> 1
ORDER BY tagId ASC

The desired return is tagId, COUNT(tagId) sorted by COUNT(tagId) DESC.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I able to do this all in the same query or am I correct in doing the counting after the results return?

>Solution :

You want one result row per tag ID, so group by tag ID. Then count.

SELECT tagId, COUNT(*) AS number_of_posts
FROM refTags 
WHERE postId IN (SELECT postId FROM refTags WHERE tagId = 1)
AND tagId <> 1 
GROUP BY tagId
ORDER BY COUNT(*) DESC;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading