I have two tables, one called Tags, the other called Posts_Tags for a many-to-many relationship. The Posts_Tags contains two columns, postid and tagid. The Tags database also contains an id column, which corresponds to the tagid in the joint table.
I’d like to get a list of tag names to display to the user, ordered by the number of times they are used. Using this information, I’ve constructed a query which joins the two tables together:
SELECT Tags.name FROM `Tags` LEFT JOIN `Posts_Tags` ON Tags.id = Posts_Tags.tagid
This gets me a list of tag names, but obviously, it doesn’t do much more than just selecting data purely from the Tags table. I know I need to add an ORDER BY clause somewhere (and possibly a GROUP BY, but I’m not sure how to construct the query.
What should I add to this query to successfully sort my results by the number of posts each tag is used in?
Use
Group ByTo count the number of times each tag is used. This assumes your tag names are unique, if not you’ll want to group on the id instead.