hello, there is a tags (varchar) field in the news table (which is sometimes empty), how can you select from the database to select the top 5 most frequently repeated tags from this field? Ie type of the most popular
1 answer
If you have one tag in the tags field, then you need to select records with a non-empty tags field ( WHERE tags IS NOT NULL ), grouped by the tags field ( GROUP BY tags ), count the number of entries in each group ( COUNT(*) ), sort the groups in descending order of quantity ( ORDER BY cnt DESC ) and take the first five groups ( LIMIT 5 )
SELECT `tags`, COUNT(*) AS `cnt` FROM `news` WHERE `tags` IS NOT NULL GROUP BY `tags` ORDER BY `cnt` DESC LIMIT 5 If it contains several tags, then you need to revise the structure of your database.
- Create a separate
tagstable with the fieldsid,name - Create a
news_tagswith the fieldsnew_id,tag_id - Remove from the
newstabletagsfield
Then your task will be solved by such a request.
SELECT t.`name` COUNT(*) AS `cnt` FROM `news_tags` nt LEFT JOIN `tags` t ON (nt.`tag_id` = t`id`) GROUP BY nt.`tag_id`, t`name` ORDER BY `cnt` DESC LIMIT 5 PS If the news tag is still one, it is still better to create a separate tags table, and rename the news.tags field to news.tag_id and make a link to the tags table
- Complete your answer with an explanation of the decision. - Yuri
- Thanks, tell me how to make it so that when choosing (in the first example), it doesn’t choose where the field is, but it turns out that emptiness comes first - turik97
- @ turik97
WHERE tags IS NOT NULL- Anton Shchyrov
|