简体   繁体   中英

MySql get list of unique words from table where values in a field separated with comma

I am not sure if this is possible with pure SQL (MySQL) but I will ask anyway. I have a table like this:

ID    TAGS
-----------------------------
1     word1,word2,word3
2     word2,word4
3     word3,word5,word6,word7
...

I would like to select a all unique words from tags field, to get out something like this:

TAGS
-----
word1
word2
word3
word4
word5
word6
word7

You can do this in SQL, although it is not pretty.

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

You need to be sure that the subquery n has at least the number of words in each tags.

Here is the SQLFiddle that demonstrates this.

This is cross joining the original data with sequential numbers. It then picks out the nth value from the tags strings, using substring_index() .

To get the maximum number of tags, you can do:

select max(length(tags) - length(replace(tags, ',', 1))+1
from t

我能想到在数据库中执行此操作的唯一方法是使用存储过程,此存储过程将遍历每一行,提取并分析其内容,但是,它不会非常有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM