简体   繁体   English

SQL查询来计数标记的帖子

[英]sql query to count tagged posts

I have a table of newsPosts where i have a column tags in that table. 我有一张newsPosts表,在该表中有一个列tags tags column contains comma(,) seperated tags like this. 标签列包含像这样的comma(,)分隔的标签。

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. 我想从新闻发布表中找到标有tag2的帖子数。

how can i do this ? 我怎样才能做到这一点 ? i am using mysql 5.0 我正在使用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. tag2应该位于结果的顶部。

Just say 说啊

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

Demo at sqlfiddle sqlfiddle上的演示

这应该工作:

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

It should work for all tags from tags table : 它应该适用于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 . 例如,它会选择具有项目tag2 ,但与mytag22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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