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

2021-11-20 00:00:00 count mysql substring

我在 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)

相关文章