利用Mysql提供的字符串方法查找字符串中某字符出现的次数

有这么一个需求,查出分类中没有子分类的一级分类,脑海中首次出现的解决思路和这样的

  1. 先使用PHP查出所有的一级分类
  2. 递归查询一级分类是否有子分类
  3. 将没有子分类的一级分类汇总

但觉的这样处理太麻烦了,然后转而在数据库层面上想办法,最后利用Mysql提供的replace、length方法完美解决
 
select name,term_id,parent,path from terms
where status = 1 and  parent = 0  --仅一级分类
--过滤掉没有子分类的分类
--length(path)-length(replace(path,'-','')) 统计path列字符串中’-‘出现的次数
--大于1表明至少有两个父分类
and  term_id not in(select parent from terms where length(path)-length(replace(path,'-',''))>1) order by listorder asc,term_id asc
 
 
 
参考:





原文地址:https://www.cnblogs.com/huangtailang/p/5923909.html