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
的记录列表。
答案 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
。