php - SELECT and ORDER BY that column using COUNT from another table -
my scenario this:
i have 3 tables structures follows:
articles: article_id, more data; tags: tag_id, tag_name, more data; article_tags: article_tag_id, tag_id, article_id
each article can have multiple tags. want retrieve tags of article (article_id provided) ordered total number of times tag used.
for eg:
article1 has tags 'tag4', 'tag3', 'tag2' article2 has tags 'tag4', 'tag3' article3 has tags 'tag4' article4 has tags 'tag4', 'tag3', 'tag2', 'tag1'
so when looking tags of article4, should order so:
1. tag4 (4 occurrences) 2. tag3 (3 occurrences) 3. tag2 (2 occurrences) 4. tag1 (1 occurrence)
is possible 1 mysql query? retrieving tags of article, array list of tags ordered occurrences, manually sorting former array using later.
i think that's
select t.tag_name, count(at.*) total tags t join article_tags @ on at.tag_id=t.tag_id t.tag_id in (select tag_id article_tags at2 at2.article_id = ?) group t.tag_name order total desc
update: added article id in clause
Comments
Post a Comment