Mysql 统计子串的实例数,然后按顺序排序

Mysql count instances of substring, then order by(Mysql 统计子串的实例数,然后按顺序排序)

本文介绍了Mysql 统计子串的实例数,然后按顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mySQL 中遇到如下问题:

I have a problem in mySQL that goes as follows:

  • 计算 mySQL 数据库中字符串字段中子字符串的实例
  • 按该子字符串 (DESC) 的出现次数对结果进行排序

除了基本的查询之外,我从未做过任何事情.我在其他地方找不到解决方案.

I have never done anything other than rudimentary queries.. I can't find a solution elsewhere.

推荐答案

SELECT (CHAR_LENGTH(str) - CHAR_LENGTH(REPLACE(str, substr, ''))) / CHAR_LENGTH(substr) AS cnt
...
ORDER BY cnt DESC

是的,看起来很臃肿,但没有任何其他可能的解决方案.

Yep, looks bloated but afaik there is no any other possible solution.

mysql> select (CHAR_LENGTH('asd') - CHAR_LENGTH(REPLACE('asd', 's', ''))) / CHAR_LENGTH('s');
+-----------------------------------------------------------------+
| (CHAR_LENGTH('asd') - CHAR_LENGTH(REPLACE('asd', 's', ''))) / CHAR_LENGTH('s') |
+-----------------------------------------------------------------+
|                                                          1.0000 |
+-----------------------------------------------------------------+
1 row in set (0.00 sec)



mysql> select host, (CHAR_LENGTH(host) - CHAR_LENGTH(REPLACE(host, 'l', ''))) / CHAR_LENGTH('l') AS cnt from user;
+-----------+--------+
| host      | cnt    |
+-----------+--------+
| 127.0.0.1 | 0.0000 |
| honeypot  | 0.0000 |
| honeypot  | 0.0000 |
| localhost | 2.0000 |
| localhost | 2.0000 |
+-----------+--------+
5 rows in set (0.00 sec)

这篇关于Mysql 统计子串的实例数,然后按顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Mysql 统计子串的实例数,然后按顺序排序