MySql 从表中获取唯一单词列表,其中字段中的值用逗号分隔

Pri*_*ome 4 mysql sql select

我不确定纯 SQL (MySQL) 是否可行,但我还是会问。我有一张这样的表:

ID    TAGS
-----------------------------
1     word1,word2,word3
2     word2,word4
3     word3,word5,word6,word7
...
Run Code Online (Sandbox Code Playgroud)

我想从标签字段中选择一个所有独特的词,得到这样的东西:

TAGS
-----
word1
word2
word3
word4
word5
word6
word7
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 5

您可以在 SQL 中执行此操作,尽管它并不漂亮。

select distinct reverse(substring_index(reverse(substring_index(tags, ',', n.n)), ',', 1)) as word
from t cross join
     (select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n) n
having word is not null
Run Code Online (Sandbox Code Playgroud)

您需要确保子查询n至少包含每个标签中的单词数。

是演示这一点的 SQLFiddle。

这是将原始数据与序列号交叉连接。然后它从标签字符串中挑选出第 n 个值,使用substring_index().

要获得最大数量的标签,您可以执行以下操作:

select max(length(tags) - length(replace(tags, ',', 1))+1
from t
Run Code Online (Sandbox Code Playgroud)