简体   繁体   中英

sql query to count tagged posts

I have a table of newsPosts where i have a column tags in that table. tags column contains comma(,) seperated tags like this.

tag1,tag2,tag3

in another table i have list of all tags under tag column like this :

tag

tag1
tag2
tag3
tag4
.
.
.
. 

I want to find number of posts from news post table which are tagged with say tag2.

how can i do this ? i am using mysql 5.0

EDIT ::

what i want to do is ::: find tags which are used highest number of times to tag a newsPost.

like this :

    tag1 x 100 times
    tag2 x 1000times
                 .
                 .
    tagN x 500 times 

tag2 should come on the top of the result.

Just say

SELECT * FROM newsPosts WHERE tags LIKE '%tag2%'

Demo at sqlfiddle

这应该工作:

SELECT * FROM newPosts WHERE tags LIKE "%tag2%"; 

It should work for all tags from tags table :

SELECT tag, (SELECT COUNT(1) 
             FROM tag_newPosts t2
             WHERE t2.tag LIKE CONCAT('%',t1.tag,'%')) AS tag_count
FROM tags t1;

You can query with regular expressions:

select *
from newsPosts
where tags regexp '(^|,)tag2(,|$)'

This expression prevents tags contained inside other tags from making it into the query results. For example, it would select items with tag2 , but not with mytag22 .

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