MySQL - 如果列值包含某些内容,则计算行数

时间:2014-11-30 10:21:15

标签: mysql

今天,当我意识到我需要计算数据库中的标签时,我就陷入了困境。我有像

这样的标签列表
tags_column
tag1
tag1,tag2

tag1,somethingElse1
somethingElse1, somethingElse2
tag2
tag3,tag1

tag2

我需要计算包含多少行的行数,例如tag1,tag2和tag3以及没有这些标记的ar行数。所以我需要像

这样的东西
$qry = "SELECT COUNT(tags_Column) AS `tag1Count` WHERE `tags_Column` CONTAINS 'tag1', 
        (SELECT COUNT(tags_Column) FROM `TableContainsTags`) AS `tag2Count` WHERE `tags_Column` CONTAINS 'tag2',
        (SELECT COUNT(tags_Column) FROM `TableContainsTags`) AS `tag3Count` WHERE `tags_Column` CONTAINS 'tag3',
        (SELECT COUNT(tags_Column) FROM `TableContainsTags`) AS `notagCount` WHERE `tags_Column` DOESN'T_CONTAINS 'tag1' OR 'tag2' OR 'tag3'
        FROM `TableContainsTags`";

请问您有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT sum( case when `tags_Column` CONTAINS 'tag2' then 1 else 0 end ) as tag2,
       sum( case when `tags_Column` CONTAINS 'tag3' then 1 else 0 end ) as tag3,
       .....
       sum( case when `tags_Column` CONTAINS 'tag256' then 1 else 0 end ) as tag256,
       sum( case when `tags_Column` CONTAINS `tag2` OR 
                      `tags_Column` CONTAINS 'tag3`
            then 0 else 1 end ) as doesnt_contains_tags_2_3
FROM `TableContainsTags`