12

簡単なクエリをしましょう:

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 |
+------------------------------+-------+
4

1 に答える 1

23

クエリで @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 ;
于 2012-08-28T10:13:52.420 に答える