在SQLite中反转文本列[已关闭]

vsaztqbk  于 2023-01-26  发布在  SQLite
关注(0)|答案(1)|浏览(173)

4天前关闭。
Improve this question
在SQLite中给定一个text列,如何反转它的值?
例如,给定此表:

CREATE TABLE "testwords" ("word" text);
INSERT INTO "testwords"("word") VALUES ('Hello'), ('world!'), ('foo bar baz');

哪些SELECT语句给出'olleH''!dlrow''zab rab oof'

ej83mcc0

ej83mcc01#

您可以使用递归CTE(对于这样一个简单的任务,这有点复杂)来完成此操作:

-- Create and populate example table:
CREATE TABLE "testwords" ("word" text);
INSERT INTO "testwords"("word") VALUES ('Hello'), ('world!'), ('foo bar baz');

-- CTE to select the reversed characters from the "testwords" table:
WITH RECURSIVE "reverse" ("stringno", "string", "charno", "char") AS (

    SELECT -- start at the last character:
        _rowid_
    ,   "word"
    ,   length("word")
    ,   substr("word", -1, 1)
    FROM "testwords"
    
    UNION ALL

    SELECT -- recurse: move one letter to the left
        "stringno"
    ,   "string"
    ,   "charno" - 1
    ,   substr("string", "charno" - 1, 1)
    FROM "reverse"
    WHERE "charno" > 1 -- stop condition
)
SELECT
    "string"
,   group_concat("char", '') AS "reversed"
FROM "reverse"
GROUP BY "stringno";

递归CTE选择每个字符串的每个字符(从右到左),并且

  • stringno是适合于对每个字符串的字符进行分组的数字
  • string是要反转的字符串
  • charno是此字符的位置(从length()向下计数到1)
  • char是字符本身

最后,使用group_concat()重新组合各个字符,得到所需的结果:

| Hello       | olleH       |
| world!      | !dlrow      |
| foo bar baz | zab rab oof |

相关问题