获取字段中出现最多字符串数的记录

时间:2011-06-27 13:32:11

标签: mysql sql ruby-on-rails

Videos Table

Title          date_published
food bag       2011-01-01
bear food bag  2010-02-02
bag mouse      2000-03-03
monitor mouse  2002-03-03

我的问题是SQL语句可以提取food字段中出现次数最多title的记录列表。

1 个答案:

答案 0 :(得分:1)

您可以使用replace技巧计算字符串出现的次数:

select  len(replace(title,'food','food+')) - len(title) as FoodCount
from    Videos

这会为每次出现添加一个额外字符,然后计算添加了多少额外字符。

此SQL Server查询选择包含最多食物的前10个视频:

select  top 10 *
from    (
        select  *
        ,       len(replace(title,'food','food+')) - len(title) as FoodCount
        from    Videos
        ) as SubQueryAlias
order by
        FoodCount desc

对于MySQL,您要移除top 10并在结尾处添加limit 10