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

前端 未结 2 1536
长情又很酷
长情又很酷 2020-12-18 09:44

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         


        
2条回答
  •  旧巷少年郎
    2020-12-18 10:41

    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
    

提交回复
热议问题