mysql 计算 sql 语法中的单词

标签 mysql

<分区>

让我们做一个简单的查询:

SELECT myfield
FROM   mytable
WHERE  criteria

例如,上面的查询给了我们 10 行结果。字段 myField 是一个文本字段。

我的问题是:是否可以更改上述查询并获取 myField 字段的总字数?

已编辑:总字数是指查询中所有选定字段在所有行中的总字数

示例

+------------------------------+-------+
| sentence                     | Words |
+------------------------------+-------+
| Hello World                  |     2 |
| Hello World                  |     2 |
| Mary had a little lamb       |     5 |
| Her fleece was white as snow |     6 |
| Everywhere that mary went    |     4 |
| Umm, sheep followed her      |     4 |
+------------------------------+-------+

最佳答案

使用this question中的优秀功能通过 @otis 在您的查询中:

mysql> select * from test;
+----+------------------------------+
| id | sentence                     |
+----+------------------------------+
|  0 | Hello World                  |
|  1 | Hello World                  |
|  2 | Mary had a little lamb       |
|  3 | Her fleece was white as snow |
|  4 | Everywhere that mary went    |
|  5 | Umm, sheep followed her      |
+----+------------------------------+
6 rows in set (0.00 sec)

mysql> SELECT sentence, wordcount(sentence) as "Words" from test;
+------------------------------+-------+
| sentence                     | Words |
+------------------------------+-------+
| Hello World                  |     2 |
| Hello World                  |     2 |
| Mary had a little lamb       |     5 |
| Her fleece was white as snow |     6 |
| Everywhere that mary went    |     4 |
| Umm, sheep followed her      |     4 |
+------------------------------+-------+
6 rows in set (0.02 sec)

要使函数生效,需要在MySQL中执行该函数的声明。这就像执行任何其他查询一样:

mysql> DELIMITER $$
mysql> CREATE FUNCTION wordcount(str TEXT)
            RETURNS INT
            DETERMINISTIC
            SQL SECURITY INVOKER
            NO SQL
       BEGIN
         DECLARE wordCnt, idx, maxIdx INT DEFAULT 0;
         DECLARE currChar, prevChar BOOL DEFAULT 0;
         SET maxIdx=char_length(str);
         WHILE idx < maxIdx DO
             SET currChar=SUBSTRING(str, idx, 1) RLIKE '[[:alnum:]]';
             IF NOT prevChar AND currChar THEN
                 SET wordCnt=wordCnt+1;
             END IF;
             SET prevChar=currChar;
             SET idx=idx+1;
         END WHILE;
         RETURN wordCnt;
       END
     $$
Query OK, 0 rows affected (0.10 sec)

mysql> DELIMITER ;

关于mysql 计算 sql 语法中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12156970/

相关文章:

php - 检查 MySQL 行中是否存在值

php - 从插入行查询返回列条目 - MySQL 和 PHP

mysql - 在 MySql 数据集中使用 for 循环

mysql - 选择列中一行中的数据

php - MYSQL + PHP : It is possible to union results from one table with data provided by an array?

java - 如何使用 Hibernate 按投影分组

php - 如何在不从 View 调用 Controller 的情况下在 codeigniter 中显示数据库中的内容?

php - Paypal IPN 数据未进入数据库

mysql - DB2转MYSQL建表脚本

mysql - Rails sql查询两个日期之间的差异超过2周