简体   繁体   中英

Getting most tagged posts

So I want to find the most posted hashtag for my post system. So here's what my posts table looks like

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| post_user    | varchar(255)     | NO   |     |         |                |
| post_ip      | varchar(255)     | NO   |     |         |                |
| post_date    | varchar(255)     | NO   |     |         |                |
| post_content | varchar(40)      | NO   |     |         |                |
| post_likes   | varchar(255)     | YES  |     | NULL    |                |
| hashtag      | varchar(255)     | YES  |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+

Now I want to query through and find the most used hashtag . So If I had two posts with the hashtag cats , it would return the number of cats, which would be 2 . Then I'd sort in descending order. So 2 for cats, and say 1 for dogs. So essentially the main question is how can I get the most "tagged", hashtag.

Your SQL would look something like:

SELECT count(hashtag) as c, hashtag FROM posts WHERE hashtag IS NOT NULL GROUP BY hashtag ORDER BY c DESC

This would return the list of hashtags, sorted by most used. The response will have two columns: c, which is the tag count and the tag itself.

If you just want the single most used tag:

SELECT count(hashtag) as c, hashtag FROM posts WHERE hashtag IS NOT NULL GROUP BY hashtag ORDER BY c DESC LIMIT 1

This table design limits you to one hashtag per post. If you wanted to allows posts to have multiple hashtags, you would need a few more tables. Hashtags and posts have a many-to-many relationship: A post can have many tags, and a tag can be used in many posts. To model this, you would need a table for hashtags, and a table that connects posts and tags. The hashtag table could have just an ID column and a column for the tag. The junction table would have a column of the post id and a column for the tag ID. To associate a tag with post, put a row in the junction table that references the tag and the post. You could then remove the hashtag column from the posts table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM