我有“单词”这个表:
id
name
insert into words values(null, 'one');
insert into words values(null, 'two');
insert into words values(null, 'three');
我需要清楚地找出整个桌子上使用的字母。 在这种情况下,结果将是:
o
n
e
t
w
h
r
我实际上并不知道如何做到这一点。我发现了一些似乎可以解决它的存储过程。对所有行进行某种迭代,其中将新字母添加到最终结果中。 有没有办法用纯sql命令执行此操作?
答案 0 :(得分:1)
您可以将SUBSTRING
与派生计数表一起使用:
SELECT DISTINCT SUBSTRING(word, n, 1) AS letter
FROM words w
CROSS JOIN
(
SELECT a.N + b.N * 10 + c.N * 1000 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) c
) n
WHERE n <= LENGTH(w.word)
ORDER BY letter;
的 SqlFiddleDemo
强>
如果您需要o
和O
作为不同的字母添加COLLATE utf8_bin
:
SELECT DISTINCT SUBSTRING(word, n, 1) COLLATE utf8_bin AS letter